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?
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?
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With