2

I have an array of objects like this :

const arr = [
  {"id" : 1, "name" : "john", "age": 12, "fruits": "banana"},
  {"id" : 2, "name" : "john", "age": 12, "fruits": "apple"}
  {"id" : 3, "name" : "maria", "age": 13, "fruits": "grappes"}
  {"id" : 4, "name" : "maria", "age": 13, "fruits": "blackberry"}
  {"id" : 5, "name" : "camille", "age": 12, "fruits": "cherry"}
]

I would like to have a single object for each person (name) and add their objects.

So the final array would be :

const arr = [
  {"id" : 1, "name" : "john", "age": 12, "fruits": ["banana", "apple"]},
  {"id" : 3, "name" : "maria", "age": 13, "fruits": ["grappes", "blackberry"]}
  {"id" : 5, "name" : "camille", "age": 12, "fruits": ["cherry"]}
];

The real array I am using is very big this is why I am looking for the most efficient way of doing this.

1
  • 1
    out of curiosity, why are the id values different for same name values and only the first id occurrence is kept? Commented May 13, 2022 at 18:50

1 Answer 1

5

You can use Array.prototype.reduce to group the objects.

const arr = [
  { id: 1, name: "john", age: 12, fruits: "banana" },
  { id: 2, name: "john", age: 12, fruits: "apple" },
  { id: 3, name: "maria", age: 13, fruits: "grappes" },
  { id: 4, name: "maria", age: 13, fruits: "blackberry" },
  { id: 5, name: "camille", age: 12, fruits: "cherry" },
];

const output = Object.values(
  arr.reduce((res, o) => {
    if (!res[o.name]) {
      res[o.name] = { ...o, fruits: [] };
    }
    res[o.name].fruits.push(o.fruits);
    return res;
  }, {})
);

console.log(output);

You can also write the above solution more succinctly:

const arr = [
  { id: 1, name: "john", age: 12, fruits: "banana" },
  { id: 2, name: "john", age: 12, fruits: "apple" },
  { id: 3, name: "maria", age: 13, fruits: "grappes" },
  { id: 4, name: "maria", age: 13, fruits: "blackberry" },
  { id: 5, name: "camille", age: 12, fruits: "cherry" },
];

const output = Object.values(
  arr.reduce(
    (res, o) => ((res[o.name] ||= { ...o, fruits: [] }).fruits.push(o.fruits), res),
    {}
  )
);

console.log(output);

Sign up to request clarification or add additional context in comments.

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.