Skip to content
Advertisement

How to combine the values which is array of the same property in the object’s array javascript

For the following array :

const a = [
  {
    26: [0],
    27: [100],
    28: [0]
  },
  {
    26: [0],
    27: [100],
    28: [0]
  },
  {
    26: [0],
    27: [100],
    28: [0]
  }
]

I need a function that should merge arrays with the same keys in the object.

`const result = [{
26: [0,0,0],
27: [100,100,100],
28: [0,0,0]
}]`

Advertisement

Answer

Try to use reduce

const data = [{
    26: [0], 27: [100], 28: [0]
  },
  {
    26: [0], 27: [100], 28: [0]
  },
  {
    26: [0], 27: [100], 28: [0]
  }
];

const restructure = arr => 
  [arr.reduce((accumu, current) => {
    for (const [key, val] of Object.entries(current)) {
      accumu[key] = [...accumu[key] ?? '', ...val];
    }
    return accumu;
  }, {})];

console.log(JSON.stringify(restructure(data)));
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement