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

Sentry image

Make it make sense

Make sense of fixing your code with straight-forward application monitoring.

Start debugging →

Top comments (0)

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay