Home > Software design >  Why is this reduce based array sum not working (JS)?
Why is this reduce based array sum not working (JS)?

Time:11-26

I've checked the answer to a similar question, but it doesn't quite solve it and I had to count on your help/expertise:

let qties = [
  [12, 45, 56, "", 45, "", "", ""]
]
const incomingBulkQty = qties[0].reduce((partialSum, a) => partialSum   a, 0);
console.log('Result: '   incomingBulkQty)

Result should be 158

I have to identify the elements' indexes as such, given my real world context.

Thanks!

CodePudding user response:

Once you add an empty string, the number is converted to a string and you're just doing subsequent string concatenation.

Here we can just wrap in Number since the string is always an empty string. Otherwise we'd also have to do an isNaN check.

let qties = [
  [12, 45, 56, "", 45, "", "", ""]
]
const incomingBulkQty = qties[0].reduce((partialSum, a) => partialSum   Number(a), 0);
console.log('Result: '   incomingBulkQty)

CodePudding user response:

It is because incomingSizes is an array and contains empty space so inside reduce callback function you are adding a number with string which will create a data type string. Any further addition will concate the string instead of number addition

let incoming = [
  [12, 45, 56, "", 45, "", "", "", null, 158]
]

const osCol = 0;
const incomingSizes = incoming.map(e => [e[osCol], e[osCol   1], e[osCol   2], e[osCol   3], e[osCol   4], e[osCol   5], e[osCol   6], e[osCol   7]])[0];
const incomingBulkQty = incomingSizes.reduce((partialSum, a) => {
  if (parseInt(a, 10)) {
    partialSum  = a
  }
  return partialSum;
}, 0);
console.log('Result: '   incomingBulkQty)

  • Related