Home > Enterprise >  How to remove duplicate elements in two dimensional array by adding the values
How to remove duplicate elements in two dimensional array by adding the values

Time:12-15

I have a two dimensional array as such

const arr = [[1664164800000,38],[1669006800000,11],[1669611600000,4],[1669611600000,12],[1670216400000,8]]

and I would like to filter the duplicate keys and add the values as such

[[1664164800000,38],[1669006800000,11],[1669611600000,16],[1670216400000,8]]

Is it possible to achieve?

CodePudding user response:

You can use reduce for this purpose

arr.reduce((acc, [key, value]) => {
  const dict = acc[1];
  if (!dict[key]) {
    const item = [key, value]; // add new item (copy value to prevent mutation of passed input)
    acc[0].push(item);
    dict[key] = item;
  } else {
    const [_, prevValue] = dict[key];
    dict[key][1] = prevValue   value; // modify/mutate item value
  }
  return acc;
}, [[], {}])[0];

CodePudding user response:

One approach would be to grab the keys from your initial array and the mapping the keys to an array where each element is [key, sumOfValuesForKey] as such:

const arr = [
  [1664164800000, 38],
  [1669006800000, 11],
  [1669611600000, 4],
  [1669611600000, 12],
  [1670216400000, 8]
];
const keys = Array.from(new Set(arr.map((el) => el[0]))); // [1664164800000, 1669006800000, 1669611600000, 1670216400000]
const summed = keys.map((key) => [key, arr.reduce((sum, el) => sum   (el[0] == key ? el[1] : 0), 0)]);
console.log(summed); // [[1664164800000,38],[1669006800000,11],[1669611600000,16],[1670216400000,8]]

  • Related