Filter array in javascript with value 0

I got an array like this:

let arr = ['1','2','0','3','0',undefined,'0',undefined,'3','',''];

To filter out the 'undefined' and '' element of this array and convert it to a number, I like it:

arr = arr.filter(function(e){
    if(e){
        return parseInt(e);
    }
});

I got:

[1,2,3,3]

0 is also filtered because 'return 0' means 'return false';

I want to know how you usually do this with this problem?

Update:

I saw that the following answers offer many useful ways. I learned a lot from him.

And if the element in the array should be a number, not a string, should I cross the array again? Or is there an alternative one-step method?

+4
source share
7 answers

You can link the required conditions.

let array = ['1', '2', '0', '3', '0', undefined, '0', undefined, '3', '', ''];

array = array
    .filter(Boolean) // get only truthy values
    .map(Number);    // convert all values to number
    
console.log(array);
Run code
+3
source

Replace

return parseInt(e);

with

return !isNaN(e);

Demo

var arr = ['1','2','0','3','0',undefined,'0',undefined,'3','',''];
var output = arr.filter(function(e){
    if(e){
        return !isNaN(e);
    }
});
console.log( output );
Run code

Edit

Number, .map( Number )

Demo

var arr = ['1','2','0','3','0',undefined,'0',undefined,'3','',''];
var output = arr.filter(function(e){
    if(e){
        return !isNaN(e);
    }
}).map( Number );
console.log( output );
+4

Easy with chain array functions:

let arr = ['1', '2', '0', '3', '0', undefined, '0', undefined, '3', '', '']
  // filter valid elements (undefined and '' evaluates to false)
  .filter(e => e)
  // to exclude '0' from the list, do a bitwise-or
  //.filter(e => e|0)
  // cast into numbers
  .map(e => e * 1);

console.log(arr);
Run code
+2
source

With slight changes

let arr = ['1','2','0','3','0',undefined,'0',undefined,'3','',''];


arr = arr.filter(function(e){
    if( parseInt(e) >=0 ){
        return  e;
    }
});
console.log(arr);
Run code
+1
source

let arr = ['1','2','0','3','0',undefined,'0',undefined,'3','',''];
let result = [];
for(let item of arr) {
  let num = +item;
  if(item === '' || Number.isNaN(num)) {
    continue;
  }
  result.push(num);
}
console.log(result);
Run code
0
source

You can use RegExp.prototype.test()with RegExp /^\d+$/to check if this value is one or more digits

arr = arr.filter(n => /^\d$/.test(n))
0
source

let arr = ['1','2','0','3','0',undefined,'0',undefined,'3','',''];

// map everything to Number (undefined becomes NaN)
// filter all valid numbers
arr = arr.map(Number).filter(e => !isNaN(e))
console.log(arr);
Run code
0
source

Source: https://habr.com/ru/post/1692083/


All Articles