Skip to content

Commit 96ba6ed

Browse files
authored
Merge pull request #26 from shailendrakanherkar18/group-by-type
Added group by key helper function
2 parents b7953b7 + a9da205 commit 96ba6ed

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

index.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -485,6 +485,46 @@ function find_key_and_update(arr, parent_key, parent_value, target_key, target_v
485485
return arr;
486486
}
487487

488+
/**
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
511+
*/
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;
526+
}
527+
488528
export {
489529
is_array,
490530
is_num_array,
@@ -512,4 +552,5 @@ export {
512552
get_rms_value,
513553
find_key_and_update,
514554
find_and_update,
555+
group_by_key,
515556
};

0 commit comments

Comments
 (0)