Combining and condensing array objects in JavaScript

I’m working with an array of objects in JavaScript. Each object has properties like ‘ru’, ‘area’, ‘unit’, and ‘tot’. I need to merge these objects based on some shared values. Here’s what I’m trying to do:

  1. Combine objects with the same ‘ru’ value.
  2. Create arrays for ‘tot’ and ‘unit’ values.
  3. Remove duplicate entries in those arrays.

For example, starting with:

let data = [
  { id: 'A1', zone: 'North', section: 'Main', count: 2 },
  { id: 'A1', zone: 'North', section: 'Main', count: 2 },
  { id: 'A1', zone: 'North', section: 'Side', count: 1 }
];

I want to end up with:

let result = [
  { id: 'A1', count: [2, 1], section: ['Main', 'Side'] }
];

What’s the best way to achieve this? I’ve tried using reduce and some nested loops, but I’m getting confused with the logic. Any help would be great!

hey guys, i think i got a simpler way. try this:

let result = data.reduce((acc, {id, section, count}) => {
  let obj = acc.find(x => x.id === id) || acc[acc.push({id, count: [], section: []}) - 1];
  obj.count.push(count);
  obj.section.push(section);
  return acc;
}, []);

this should do what u want. it groups by id and puts everything in arrays. u might need to remove dupes after tho

I’ve tackled a similar problem in one of my projects. The key is to use reduce() effectively. Here’s an approach that worked well for me:

const result = data.reduce((acc, curr) => {
  const existingItem = acc.find(item => item.id === curr.id);
  if (existingItem) {
    existingItem.count = [...new Set([...existingItem.count, curr.count])];
    existingItem.section = [...new Set([...existingItem.section, curr.section])];
  } else {
    acc.push({ id: curr.id, count: [curr.count], section: [curr.section] });
  }
  return acc;
}, []);

This method efficiently combines objects with the same ‘id’, creates arrays for ‘count’ and ‘section’, and removes duplicates using Set. It’s concise and handles the logic in a single pass through the data. Remember to adjust the property names if they differ in your actual data structure. Hope this helps solve your problem!

I’ve encountered this issue before in a data processing project. Here’s an efficient solution using Object.values() and reduce():

const result = Object.values(data.reduce((acc, {id, zone, section, count}) => {
  if (!acc[id]) {
    acc[id] = {id, count: new Set(), section: new Set()};
  }
  acc[id].count.add(count);
  acc[id].section.add(section);
  return acc;
}, {})).map(item => ({
  ...item,
  count: Array.from(item.count),
  section: Array.from(item.section)
}));

This approach first groups the data by id, then converts Sets to Arrays. It’s performant for large datasets and avoids nested loops. The final output matches your desired format exactly. Make sure to adjust property names if your actual data structure differs.