Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript parsing array of object into a group by array

I’m looking for a way to parse an array of objects,
with common object key into a new array with an object with the common key and an array of the common objects.
the array looks like this:

[
{
 "name":"Elon",
 "city":"Berlin",
 "salary":5000,
 "age":25
},
{
 "name":"John",
 "city":"Amsterdam",
 "salary":8700,
 "age":28
},{
 "name":"Jacob",
 "city":"Berlin",
 "salary":6500,
 "age":28
},{
 "name":"Lilly",
 "city":"Amsterdam",
 "salary":10000,
 "age":23
},{
 "name":"Mika",
 "city":"Kiev",
 "salary":6800,
 "age":25
}
]

I want to parse it that the array will look like this:

[
{
"city":"Amsterdam",
"ppl":[
{
 "name":"John",
 "salary":8700,
 "age":28
},{
 "name":"Lilly",
 "salary":10000,
 "age":23
}]
},{
"city":"Berlin",
"ppl":[{
 "name":"Elon",
 "salary":5000,
 "age":25
},{
 "name":"Jacob",
 "salary":6500,
 "age":28
}]
},{"city":"Kiev",
"ppl":[{
"name":"Mika",
 "city":"Kiev",
 "salary":6800,
 "age":25
}]}

I’ve tried using reduce or forEach but it messed up.
Any idea or guideness?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use Array#reduce with an object to store the people in each city.

const arr=[{"name":"Elon","city":"Berlin","salary":5000,"age":25},{"name":"John","city":"Amsterdam","salary":8700,"age":28},{"name":"Jacob","city":"Berlin","salary":6500,"age":28},{"name":"Lilly","city":"Amsterdam","salary":10000,"age":23},{"name":"Mika","city":"Kiev","salary":6800,"age":25}];
let res = Object.values(arr.reduce((acc, {city, ...rest})=>
  ((acc[city] ??= {city, ppl: []}).ppl.push(rest), acc), {}));
console.log(res);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading