I have two arrays:
const data = [ 250, 250, 500, 500 ]
const labels = [ '2022-05-10', '2022-06-10', '2022-07-10', '2022-07-10' ]
Each date in the labels array has a corresponding value in the data array, and I need to sum the values for each day that's the same, so the output should look like this:
const data = [ 250, 250, 1000 ]
const labels = [ '2022-05-10', '2022-06-10', '2022-07-10' ]
How can I do this?
const labels = ['2022-05-10', '2022-06-10', '2022-07-10', '2022-07-10'];
const data = [250, 250, 500, 500];
const restructure = (keysArray, valuesArray) =>
keysArray.reduce((accumu, current, index) => {
current = { [current]: valuesArray[index] };
for (const [key, val] of Object.entries(current)) {
accumu[key] = (accumu[key] ?? 0) + val;
}
return accumu;
}, {});
const prettyPrint = (title, obj) =>
console.log(`${title} =>`, JSON.stringify(obj));
const result = restructure(labels, data);
prettyPrint('labels', Object.keys(result));
prettyPrint('data', Object.values(result));
const data = [ 250, 250, 500, 500 ];
const labels = [ '2022-05-10', '2022-06-10', '2022-07-10', '2022-07-10' ];
var newData = new Array();
var newLabels = new Array();
labels.forEach(myFunction);
newLabels.forEach(myFunction2);
function myFunction(item,index) {
console.log(item + ',' + index);
if(!newLabels.includes(item) ) {
newLabels.push(item);
newData.push(data[index]);
}
else {
var newIndex = newLabels.indexOf(item);
console.log(newIndex);
var added = newData[newIndex] + data[index];
newData[newIndex] = added;
}
}
function myFunction2(item,index){
console.log(item + ',' + index);
console.log(newData[index]);
}
My javascript is pretty rusty, but this zips the two arrays together, and then creates an object where I add to the object if that key already exists, or create it if it doesn't. (That might be what a proper reduce answer does?)
zip = (...rows) => [...rows[0]].map((_, c) => rows.map(row => row[c]))
let data = [250, 250, 500, 500]
let labels = ['2022-05-10', '2022-06-10', '2022-07-10', '2022-07-10']
const values = zip(labels, data)
const output = {}
for (const [date, value] of values) {
if (Object.keys(output).includes(date)) {
output[date] += value
}
else {
output[date] = value
}
}
data = Object.values(output)
labels = Object.keys(output)
console.log(data)
console.log(labels)