OblongMedulla
OblongMedulla

Reputation: 1595

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

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

Upvotes: 0

Views: 44

Answers (2)

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27232

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

Upvotes: 1

OblongMedulla
OblongMedulla

Reputation: 1595

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]))}

Upvotes: 0

Related Questions