Jobelle
Jobelle

Reputation: 2834

Javascript filter not returning the expected int value

The JavaScript filter function not converting the item to integer by using the parseInt. Because of that string concatenation is going on rather than adding the values when used the filtered array in reduce function.

    var numbers = ['1', 2, 3, 4,'hello'];

    var intArray=numbers.filter(num => **parseInt(num)**);

    var sum=intArray.reduce((tot, b) => tot+b,0);

Upvotes: 0

Views: 592

Answers (3)

Akrion
Akrion

Reputation: 18515

You can also sum them in one reduce and skip the filter stage where "1" gets passed as valid value (which as pointed out already is the issue) etc.

var numbers = ['1', 2, 3, 4,'hello'];
const result = numbers.reduce((r,c) => (+r||0) + (+c||0))
console.log(result)

Upvotes: 0

Raj Nandan Sharma
Raj Nandan Sharma

Reputation: 3862

The trick is to first filter out non int values and then convert all of them to int filter with isNaN would eliminate hello and map with parseInt will convert strings o number to int

var numbers = ['1', 2, 3, 4, 'hello'];
var intArray = numbers
  .filter(num => !isNaN(num)).map(x => parseInt(x))

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370729

Your filter is filtering out the items that cannot be coerced to a number, but the items are still not necessarily numbers - convert them to numbers before using + with them, perhaps with .map:

var numbers = ['1', 2, 3, 4, 'hello'];
var intArray = numbers
  .filter(num => parseInt(num))
  .map(Number);
var sum = intArray.reduce((tot, b) => tot + b, 0);
console.log(sum);

Or, you can do it all at once with reduce and isNaN:

var numbers = ['1', 2, 3, 4, 'hello'];
var sum = numbers.reduce((tot, b) => {
  if (isNaN(b)) return tot;
  return tot + Number(b);
}, 0);
console.log(sum);

Upvotes: 1

Related Questions