Last updated: Jul 25, 2022
Photo from Unsplash
filter() method to filter an array to only numbers, e.g.
arr.filter(value => typeof value === 'number'). The
filter method returns an
array with all the elements that satisfy the condition. In our case, all array
elements with a type of
const arr = [1, 'test', 3, null]; const onlyNumbers = arr.filter( element => typeof element === 'number' ); console.log(onlyNumbers); // 👉️ [1, 3]
The function we passed to the Array.filter method gets called with each element in the array.
If the function returns a truthy value, the element gets added to the new array
filter() method returns.
On each iteration, we check if the element has a type of
number using the
typeofoperator returns a string that indicates the type of a value.
All the elements that meet the condition (have a type of number) will get added to the new array.
If you have an array of strings that might be valid numbers, you can pass the
Number object to the
const arr = ['1', 'test', '3', 5]; const validNumbers = arr.filter(Number); // 👇️ ['1', '3', 5] console.log(validNumbers); const toNumbers = validNumbers.map(Number); console.log(toNumbers); // 👉️ [1, 3, 5]
We used the
filter method to iterate over the array. On each iteration, we
convert the element to a number and return the result.
Numberobject takes the current element, converts it to a number and returns the result.
Note that if a value of
0 is passed to the number object, it wouldn't get
included in the new array because
0 is a falsy value.
NaN (not a number).
filter method doesn't convert the strings in the array to numbers, it
simply returns the elements that meet the condition.
You can call the
map() method on the filtered array to get an array of