Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is this reduce based array sum not working (JS)?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks!

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading