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

Sum negative and positive numbers in array to get a result

i’m stucked with a simple logic, i have an array as a result that contains positive and negative numbers.

what i need is to sum both negative and positive and print a result

const arr = ['-8', '-3', '1', '-4', '0']
// expected results = -14

what i’ve tried so far is to separate negative and positive with:

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

 const positive = scores.filter(posNumber => posNumber >= 0)
 const negative = scores.filter(negNumber => negNumber < 0)

but if i perform a reduce on positive i get "010" as a result….

>Solution :

The problem here is that your array is actually an array of strings instead of numbers. So in reality, you need to convert the array to an array of numbers and then you can sum the values.

const arr = ['-8', '-3', '1', '-4', '0'];
const sum = arr.reduce((acc, value) => acc + Number(value), 0); // -14
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