Dark Mode
Enable Console
filterNums(list)
/*
Takes an array list as input and returns a new array
with only numbers and drops everything else.
*/
filterNums([5, 10, 'hello', 'world']);
// [5, 10]
filterNums(['get', 1, 'only', 2, 'nums']);
// [1, 2]
Solution by - Need4Swede
filterNums(list){
// Initialize a an empty array
let numArr = [];
// Push all numbers to the new array
list.forEach(element => {
if (Number.isFinite(element)){
numArr.push(element);
};
});
// Return the new array
return numArr;
}
Alternatively, you can write it like this...
function filterNums(list) {
return list.filter(Number.isInteger);
}
Try it yourself - Codewars Source