Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter an array in javascript with value 0

Tags:

javascript

I got an array like this:

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

In order to filter the 'undefined' and '' element of this array and convert it to a number, I do like this:

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

I got:

[1,2,3,3]

The 0 has also been filtered because 'return 0' means 'return false';

I want to know how do you normally do with this kind of problem?

Update:

I saw the following answers propose many useful ways. I learned a lot from it.

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

like image 484
htxu Avatar asked Dec 23 '22 11:12

htxu


1 Answers

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

Edit

For converting the values to Number as well, just add .map( Number ) to the filter output

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 );
like image 157
gurvinder372 Avatar answered Jan 09 '23 06:01

gurvinder372