Home > OS >  Why is the array concatenating the numbers -vs- adding them as I would like
Why is the array concatenating the numbers -vs- adding them as I would like

Time:08-02

I have tried several methods and am not understanding why I cant simple get the sum of the numbers in my array. I.E.

Logger.log(shirtColor)
Logger.log(shirtColor.reduce((a, b) => a   b, 0))

Logger shows:

Info    [0.0, 1, 2, 1]
Info    0121

CodePudding user response:

I was able to use the comments to understand my oversight. I was pushing data that was a string. Instead the data I was pushing I added Number()

if (vs[i][15] > 0) {
            shirtColor.push(Number(vs[i][15]))}

CodePudding user response:

Looks like shirtColor array contains string elements. That's the reason it is appending as a string.

If shirtColor is an array of string elements.

const arr = ['1', '2', '1'];

const res = arr.reduce((a, b) => a   b, 0);

console.log(res); // 0121

If shirtColor contains numeric elements.

const arr = [0.0, 1, 2, 1];

const res = arr.reduce((a, b) =>  a    b, 0);

console.log(res); // 4

To achieve the requirement, You can convert a string to a number in JavaScript using the unary plus operator ( ).

const arr = ['0.0', '1', '2', '1'];

const res = arr.reduce((a, b) =>  a    b, 0);

console.log(res);

  • Related