DEV Community

Sharu
Sharu

Posted on

Arrays and Objects in JS

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 }, ] }
] 
Enter fullscreen mode Exit fullscreen mode

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);

Enter fullscreen mode Exit fullscreen mode

Top comments (0)