[SOLVED] How to group array of objects by certain property values

Issue

I have a two arrays.
One array with strings which contains names

let companies = ['Google', 'Coca Cola,' 'Jonson & Jonson',];

And another array contains objects with people

let employees = [
  {name: 'Alina' company: 'Google', id : 1},
  {name: 'Vika' company: 'Coca Cola', id : 2},
  {name: 'Alex' company: 'Jonson & Jonson', id : 3},
  {name: 'Vlad' company: 'Google', id : 4},
  {name: 'Fibi' company: 'Coca Cola', id : 5},
  {name: 'Joey' company: 'Google', id : 6},
]

And my task is to group those people by names

const groups = [
 {'Google': [
   {name: 'Alina' company: 'Google', id : 1},
   {name: 'Vlad' company: 'Google', id : 4},
 ]},
 'Jonson & Jonso': [
   {name: 'Alex' company: 'Jonson & Jonson', id : 3},
 ]},
 ...
]

Maybe anyone knows how to do it the simplest way and without extra iterations for JS ?
I could use a nested loops but it would be too complicated.
Maybe it’s possible to do with lodash ?
Also please note that string keys for company names may have spaces.
Will be very grateful for any advices.

Solution

A back to the future answer :

Not yet supported by lot of browsers but will come soon (Stage 3 for TC39) and already available in polyfill core-js) is the new groupBy method on the array object.

This will allows you to do it directly like this :

employees.groupBy(employee => employee.company);

or even :

employees.groupBy(({company}) => company);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/groupBy

Answered By – Michel Lamsoul

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *