简体   繁体   中英

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 this array:

array_new: ,102.80,192.60,22.16

then I do this:

var sum = array_new.reduce((a, b) => a + b, 0);
  console.log(sum); //gives me this 0,102.80,192.60,22.16

When all I want to do is add up the numbers, I get this result 0,102.80,192.60,22.16. Can anyone advise me?

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.

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

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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM