简体   繁体   中英

How to group array of objects by certain property values

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.

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

 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}, ] function groupBy(arr, property) { return arr.reduce(function (memo, x) { if (!memo[x[property]]) { memo[x[property]] = []; } memo[x[property]].push(x); return memo; }, {}); }; console.log(groupBy(employees,'company'));

The simplest way would be:

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},
]

const grouped = groupBy(employees, employee => employee.company);

Mate, it seems like no respect for potential responders, if u don't even check if ur structures are free of errors, before asking a question. Nvm :/

So, there are fixed variables:

let companies = ['Google', 'Coca Cola', 'Jonson & Jonson'];
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}]

Please notice that companies is redundant, as all the needed info is in employees .

The structure that you are looking for is probably Map . You simply do:

let map = new Map()
employees.forEach((currentValue) => {
    map.has(currentValue.company) 
    ? map.get(currentValue.company).push({name: currentValue.name, id: currentValue.id})
    : map.set(currentValue.company, [{name: currentValue.name, id: currentValue.id}])
});

to get this result (field company won't be needed anymore in employee object):

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

Since you are going the simple route it would be slightly long.

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

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},
]

//Let's create an intermediate object 
let interm = {};
/*This would create an object like 
 {
 Key:[],
 Key2:[],
 ...
 }

*/
companies.forEach((each)=>{
    interm[`${each}`] = [];
})

/*filling that interm a
Object with values like

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

*/

employee.forEach((each)=>{
    if(companies.indexOf(each.company) != -1)
    interm[`${each.company}`].push(each)

})

//Now our intermediate data is ready 
//We need to convert to our   desirable format
let finalArray = []
Object.keys(interm).forEach((each)=>{
    finalArray.push({each:interm[`${each}`]})
})

console.log(finalArray)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM