Skip to content

Commit 99cbfeb

Browse files
authored
Merge pull request #27 from SanjayBoricha/add-group-by-func
Added group_by function
2 parents 96ba6ed + f973ae1 commit 99cbfeb

File tree

1 file changed

+12
-37
lines changed

1 file changed

+12
-37
lines changed

index.js

Lines changed: 12 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -486,43 +486,18 @@ function find_key_and_update(arr, parent_key, parent_value, target_key, target_v
486486
}
487487

488488
/**
489-
* Group by key will group data by given key
490-
*
491-
* e.g i/p [
492-
* {type: 'Movie', value: 'M1'},
493-
* {type: 'TV show', value: 'TS1'},
494-
* {type: 'Movie', value: 'M2'},
495-
* {type: 'TV show', value: 'TS2'},
496-
* ]
497-
* o/p
498-
*
499-
* {
500-
* Movie: [
501-
* {type: 'Movie', value: 'M1'},
502-
* {type: 'Movie', value: 'M1'},
503-
* ],
504-
* 'TV show': [
505-
* {type: 'TV show', value: 'TS1'},
506-
* {type: 'TV show', value: 'TS2'},
507-
* ]
508-
* }
509-
* @param {array of obejcts} input_arr
510-
* @param {string} key
489+
* Group by key in array of object
490+
*
491+
* @param array arr
492+
* @param string key
493+
* @returns object
511494
*/
512-
function group_by_key(input_arr, key) {
513-
let result = {};
514-
515-
result = input_arr.reduce((obj, item) => {
516-
// if key already present in obj and push the new item
517-
if (obj[item[key]]) {
518-
obj[item[key]].push(item)
519-
} else {
520-
// if we don't find a key inside an obj, Then add key into object with value as an array
521-
obj[item[key]] = [item]
522-
}
523-
return obj;
524-
}, {})
525-
return result;
495+
function group_by(arr, key) {
496+
is_array(arr)
497+
return arr.reduce(function (rv, x) {
498+
(rv[x[key]] = rv[x[key]] || []).push(x);
499+
return rv;
500+
}, {});
526501
}
527502

528503
export {
@@ -552,5 +527,5 @@ export {
552527
get_rms_value,
553528
find_key_and_update,
554529
find_and_update,
555-
group_by_key,
530+
group_by,
556531
};

0 commit comments

Comments
 (0)