Home > database >  The sum of the same values in a field next to each other
The sum of the same values in a field next to each other

Time:07-18

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?

CodePudding user response:

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]);
}

CodePudding user response:

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));

  • Related