• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

126
Views
In an array of objects how to group objects which have same value and include the values that differ

I have an array of objects and I would like to group the objects which have same name and make an array containing the other values which differs. How can I achieve that?

const arr = [
  {
    name: 'A',
    color: 'blue',
  },
  {
    name: 'A',
    color: 'purple',
  },
  {
    name: 'B',
    color: 'Yellow',
  },
  {
    name: 'B',
    color: 'Green',
  },
];

What I would like to get:

const result = [
  {
    name: 'A',
    color: ['blue', 'purple'],
  },
  {
    name: 'B',
    color: ['Yellow', 'Green'],
  },
];
almost 3 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Here is one way to do it:

const arrNames = Array.from(new Set(arr.map((x) => x.name))); // make an array of unique names
const result = arrNames
  .map((x) => arr.filter((y) => y.name === x)) // filter by name
  .map((x, i) => ({ name: arrNames[i], color: x.map((y) => y.color) })); // make new objects 
almost 3 years ago · Juan Pablo Isaza Report

0

  const found = acc.find(item => item.name === curr.name);
  if (found) {
    found.color.push(curr.color);
  } else {
    acc.push({
      name: curr.name,
      color: [curr.color],
    });
  }
  return acc;
}
  , []);
almost 3 years ago · Juan Pablo Isaza Report

0

This looks like something reduce() should be used for. Use find() to find in the existing array element based on some condition. If element exists, push into colors property of the element. Else push into the array a new object.

const arr = [
  {
    name: 'A',
    color: 'blue',
  },
  {
    name: 'A',
    color: 'purple',
  },
  {
    name: 'B',
    color: 'Yellow',
  },
  {
    name: 'B',
    color: 'Green',
  },
];


let ans = arr.reduce((agg,curr) => {
let found = agg.find((x) => x.name === curr.name);
if(found){
  found.colors.push(curr.color);
}
else{
   agg.push({
   name : curr.name,
   colors : [curr.color]
   });
}
return agg;
},[]);

console.log(ans);

almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error