Create a function that takes a list of non-negative integers and strings and returns a new list with the strings filtered out. When I pass [1,'a','b',0,15]
, it returns [1,15]
instead of [1,0,15]
. Please suggest any corrections.
function filter_list(l) {
// Return a new array with the strings filtered out
var filt = l.filter(function(x) {
if (typeof(x) === 'number')
return x;
});
return filt;
}
0 is falsey, and if the value returned by the filter
callback is falsey, the item being iterated over will not be included in the final array. Simply return typeof x === 'number'
instead:
function filter_list(l) {
return l.filter(x => typeof x === 'number');
}
console.log(filter_list([1, 'a', 'b', 0, 15]));