Y
Y
YakovSpb2021-06-11 17:16:18
JavaScript
YakovSpb, 2021-06-11 17:16:18

How to group an array of objects by the values ​​of one of their properties?

There is an array:

const persons = [
  { name: 'Alex', age: 20 },
  { name: 'Lena', age: 25 },
  { name: 'Pavel', age: 20 }
]

Need to get:

{
  20: [{ name: 'Alex', age: 20 }, { name: 'Pavel', age: 20 } ],
  25: [{ name: 'Lena', age: 25 }]
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
n1ksON, 2021-06-11
@YakovSpb

const persons = [
{ name: 'Alex', age: 20 },
{ name: 'Lena', age: 25 },
{ name: 'Pavel', age: 20 }
]

let obj = {}
persons.forEach(v => {
    if (v.age in obj) {
      let arr = obj[v.age];
      arr.push(v);
      obj[v.age] = arr;
    } else { 
      obj[v.age] = [v] 
    }
})

S
Sergey delphinpro, 2021-06-11
@delphinpro

You would find the answer faster in a search engine
https://yandex.ru/search/?text=javascript%20how%20...
Here, right at the top of the issue https://stackoverflow.com/questions/54177679/how-t.. .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question