Arrays and Objects in JS
Sharu
Posted on January 23, 2023
Given an input array which stores names and respective age as an object, how can one group these objects into respective age groups.
Problem Statement
//Example Input :
let people = [
{ name: "sumit", age: 17 },
{ name: "rajesh", age: 24 },
{ name: "akbar", age: 44 },
{ name: "ali", age: 44 },
];
//Expected Output:
[
{ '17': [ { name: "sumit", age: 17 } ] },
{ '24': [ { name: "rajesh", age: 24 } ] },
{ '44': [ { name: "akbar", age: 44 },
{ name: "ali", age: 44 }, ] }
]
Highlights / Explanation:
First task here is to identify the structural pattern of the result set - Clearly these Objects are enclosed in an array for every age group and the age group is an object enclosed in the resultant array.
Secondly, we need to loop through the objects in the input array to group individuals by age group by looking up the result array
let people = [
{ name: "sumit", age: 17 },
{ name: "rajesh", age: 24 },
{ name: "akbar", age: 44 },
{ name: "ali", age: 44 },
];
let index = -1,
age;
let result = people.reduce((acc, ele) => {
age = ele.age;
index = acc.findIndex((ele) => Object.keys(ele).toString() == age);
if (index == -1) {
acc.push({ [age]: [].concat(ele) });
} else {
acc[index][age].push(ele);
}
return acc;
}, []);
console.log(result);
đź’– đź’Ş đź™… đźš©
Sharu
Posted on January 23, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript Unlocking Better JavaScript Performance: Avoid These Common Pitfalls 🚀
November 24, 2024
javascript Goodbye Exceptions! Mastering Error Handling in JavaScript with the Result Pattern
November 22, 2024