ReactJS: Help debugging? Sum of each array NOT columns

Viewed 95

Need help with figuring out how to get the sum of multiple arrays.

This is my Data outputting from the console.log:

(4) [empty, Array(1), Array(1), Array(4)]
1: [50, 30]
2: [100, 100, 50]
3: (4) [500, 10, 50, 300]

Expected output:

1: [80] 
2: [250] 
3: [860]

Methods used:

  1. This code below doesn't work, it's just the columns of each row

    const savingsTotal = saveID[0].map((x, idx) => saveID.reduce((sum, curr) => sum + curr[idx], 0));
    

code source : How to calculate the sum of multiple arrays?

  1. This code gives me a weird string:

     const savingsTotal = saveID.reduce((sum, value) =>  sum += value, 0)
    

Output: 050100500,10,50,300

  1. Thought if I list with a key that would work, eg [saved: 500], but it didn't up working either.

     const savingsTotal = saveID.map(({saved}) => saved.reduce((sum, value) => sum += value, 0))
    

Output: breaks code, can't find [saved : 500] due to the previous function which is:

  if (save.length > 0 ) { 
  const saveID = save.reduce((savedAmount, { goal_id, saved }) => {
    (savedAmount[goal_id] = savedAmount[goal_id] || []).push({"saved": saved});
    return savedAmount;
  }, []); ****Changed the .push so I would be able to add a key, normally it's without. 

code source: How to get a the sum of multiple arrays within an array of objects?

Can someone help me out with the logic?

3 Answers

Map through the original array of arrays. then use reduce to get the respective sum of their parts:

const ar = [[50, 30], [100, 100, 50], [500, 10, 50, 300]];
const sum_array = ar.map(item => item.reduce((acc, val) => acc + val, 0))
console.log(sum_array)

You can loop over the outer array and use reduce to find the sum of each constituent array.

const arr = [, [50, 30],[100, 100, 50], [500, 10, 50, 300]];
for(let i = 0; i < arr.length; i++){
  if(Array.isArray(arr[i])){
    console.log(i + ': ' + arr[i].reduce((acc,curr)=>acc+curr, 0));
  }
}

If you want to produce a result array instead of just printing it, you can use map.

const arr = [, [50, 30],[100, 100, 50], [500, 10, 50, 300]];
const res = arr.map(x => x.reduce((acc,curr)=>acc+curr, 0));
console.log(res);

Try this:

let arr = [10, 70],
    arr2 = [100, 100, 50],
    arr3 = [500, 10, 50, 300]

console.log(arr.reduce((sum, carry) => sum + carry));
console.log(arr2.reduce((sum, carry) => sum + carry));
console.log(arr3.reduce((sum, carry) => sum + carry));

Related