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?
>Solution :
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];