Skip to content Skip to sidebar Skip to footer

Add Up Numbers In Array

I've been following this post but I cannot get my array to add up all numbers in my array. I use this: var array_new = [$('.rightcell.emphasize').text().split('€')]; to give me

Solution 1:

Since your array is composed of undefined and a bunch of strings you have to parse the values to get the numbers. The answer would be:

var data = [,'102.80','192.60','22.16'];

console.log(data.reduce((r,c) => r + parseFloat(c), 0))

However if you do not want to deal with the parsing in that function you can make sure that your array comes out as array of numbers like this:

Array.from([$(".rightcell.emphasize").text().split('€')], (x) => parseFloat(x || 0))

Which would get your array ready for summation and without the need to parse inside the Array.reduce. So it would be something like this:

var strings = [,'102.80','192.60','22.16'];
var numbers = Array.from(strings, (x) => parseFloat(x || 0))

console.log(numbers.reduce((r,c) => r + c, 0))

But in your case it would be shorter since you would do the first 2 lines as one as shown in the 2nd code snippet.


Solution 2:

Your elements in the array are treated as strings, therefore the + in your reduce function concatenates the array elements into another string. Try to use parseFloat() to treat them as numbers:

var sum = array_new.reduce((a, b) => a + parseFloat(b), 0);

EDIT: Thanks to charlietfl who mentioned, that parseFloat(a) is redundant, fixed it.

EDIT: (since you already deleted your comment, here would be the solution for your problem): in your case this solution won't work, because one of your array elements is "" (an empty string) which can't be treated as a number, so you could map your array values before you try to add them up:

array_new.map(a => (a == "") ? "0" : a);

Solution 3:

That's because your original array is a string array.

Use parseFloat to create numbers from the strings.

var strArr = ['102.80','192.60','22.16'];
var sum = strArr.reduce((a,b) => a + parseFloat(b),0); // 317.56

Solution 4:

in javascript, you can concat numbers by + or strings as well . I will give you an example :

var x = "2" + "1"; // x = 21
var x = 2 + 1 ; // x = 3

You can look to this.

You should convert your array to integers (parseInt) or floats(parseFloat) in this function array_new.reduce((a, b) => a + b, 0); It will be something like

array_new.reduce((a, b) => a + parseInt(b), 0);//or
array_new.reduce((a, b) => a + parseFloat(b), 0);

Post a Comment for "Add Up Numbers In Array"