2

if I have a js array like below, is there a simple way to re-group the array values by age? I tried to reduce it to an array but it did not help. it's re-grouped with age or name's

let employees = [
 {
  firstName:"Zion",
  lastName: "Rosy",
  age: 25,
  joinedDate:"January 24, 2020",
 },

 {
  firstName: "Ana",
  lastName: "Rosy",
  age: 25,
  joinedDate: "January 15, 2019",
 },

 {
  firstName: "Zion",
  lastName:"Albert",
  age: 30,
  joinedDate:"February 15, 2011",
 },
];

To re-group by age like this:

let organizedByAge =
 {
  25: [
 {
  firstName:"Zion",
  lastName: "Rosy",
  age: 25,
  joinedDate:"January 24, 2020",
 },
 {
  firstName: "Ana",
  lastName: "Rosy",
  age: 25,
  joinedDate: "January 15, 2019",
 },
  ],

  30: [
   {
    firstName:"Zion",
    lastName:"Albert",
    age: 30,
    joinedDate:"February 15, 2011",
   },
  ],
 };
1

3 Answers 3

4
const groupByKey = (_data, _key) => {
  return _data.reduce((result, next) => {
    const key = next[_key];
    result[key] = result[key]?.length ? [...result[key], next] : [next];
    return result;
  }, {});
  }

 console.warn(groupByKey(employees, 'age'));
Sign up to request clarification or add additional context in comments.

Comments

3

Using Array#reduce:

const employees = [
  { firstName:"Zion", lastName: "Rosy", age: 25, joinedDate:"January 24, 2020" },
  { firstName: "Ana", lastName: "Rosy", age: 25, joinedDate: "January 15, 2019" },
  { firstName: "Zion", lastName:"Albert", age: 30, joinedDate:"February 15, 2011" }
];

const organizedByAge = employees.reduce((map, e) => ({
  ...map,
  [e.age]: [...(map[e.age] ?? []), e]
}), {});

console.log(organizedByAge);

Comments

2

is there a simple way to re-group the array values by age?

When rewriting arrays and objects, the most straightforward and readable approach is often to use a simple for loop:

for (let i = 0; i < employees.length; i++) {
  
  const age = employees[i]['age'];
  
  if (organizedByAge.hasOwnProperty(age)) {
    organizedByAge[age].push(employees[i]);
  }
  
  else {
    organizedByAge[age] = [];
    organizedByAge[age][0] = employees[i];
  }
}

Working Example:

let employees = [
 {
  firstName:"Zion",
  lastName: "Rosy",
  age: 25,
  joinedDate:"January 24, 2020",
 },

 {
  firstName: "Ana",
  lastName: "Rosy",
  age: 25,
  joinedDate: "January 15, 2019",
 },

 {
  firstName: "Zion",
  lastName:"Albert",
  age: 30,
  joinedDate:"February 15, 2011",
 },
];

let organizedByAge = {};

for (let i = 0; i < employees.length; i++) {
  
  const age = employees[i]['age'];
  
  if (organizedByAge.hasOwnProperty(age)) {
    organizedByAge[age].push(employees[i]);
  }
  
  else {
    organizedByAge[age] = [];
    organizedByAge[age][0] = employees[i];
  }
}

console.log(organizedByAge);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.