I have a 2D array that contains values like this:
var array = [["10/10/2020","1000"],["10/10/2020","300"],["07/10/2020","100"],["07/10/2020","100"],["03/10/2020","100"],["10/10/2020","100"]];
For every nested array that has the same date value (the first element), I want to add up the second value to have something like this:
arrayAdd = [["10/10/2020","1400"],["O7/10/2020","200"],["03/10/2020","100"]]
How can I do this?
Step by step:
Create an empty object/map.
Iterate over your array.
Get the first element of each item in the array (date) and check if that key is already in the object.
If it is not, you add it. The value will be the second element (the number).
If it is there already, you increment the value.
Object.entries will turn that object into an array with the shape you want, as you can see below:
const obj = {
"10/10/2020": "1400",
"O7/10/2020": "200",
"03/10/2020": "100",
};
console.log(Object.entries(obj));
.as-console-wrapper {
max-height: 100% !important;
}
This should help you get started.
var array = [["10/10/2020","1000"],["10/10/2020","300"],["07/10/2020","100"],["07/10/2020","100"],["03/10/2020","100"],["10/10/2020","100"]];
function fromEntries (iterable) {
return [...iterable].reduce((obj, [key, val]) => {
obj[key] = String(obj[key] ? +obj[key] + +val : val)
return obj
}, {})
}
console.log(fromEntries(array))
function mergeDates(array) {
// create empty object mapping given data like {date: value, ...}
const accumulator = {};
// iterate over all date value pairs
for (const [date, value] of array) {
// if accumulator already has date as key: add value
if (date in accumulator) accumulator[date] += parseInt(value);
// if not: add key with value
else accumulator[date] = parseInt(value);
}
// turn {date: value, ...} into [[date, value], ...]
return Object.entries(accumulator)
// ...and convert value from integer into a string
.map(([date, value]) => [date, value.toString()]);
}
console.log(mergeDates(
[["10/10/2020","1000"],["10/10/2020","300"],["07/10/2020","100"],["07/10/2020","100"],["03/10/2020","100"],["10/10/2020","100"]]
));
// expected results: [["10/10/2020","1400"],["07/10/2020","200"],["03/10/2020","100"]]