@@ -485,6 +485,46 @@ function find_key_and_update(arr, parent_key, parent_value, target_key, target_v
485
485
return arr ;
486
486
}
487
487
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
+
488
528
export {
489
529
is_array ,
490
530
is_num_array ,
@@ -512,4 +552,5 @@ export {
512
552
get_rms_value ,
513
553
find_key_and_update ,
514
554
find_and_update ,
555
+ group_by_key ,
515
556
} ;
0 commit comments