Answer the question
In order to leave comments, you need to log in
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 }
]
{
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
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]
}
})
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 questionAsk a Question
731 491 924 answers to any question