Sat Nov 13 2021·2 min read
Photo by Henry Lai
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 elements 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 of the elements that satisfy the condition (have a type of number) will be 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 use the
filter method to iterate over the array and on each iteration, we
convert the element to a number and return the result.
Number object 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 would not get
included in the new array because
0 is a falsy value.
NaN (not a number).
filter()method would return the valid numbers as is, but we can use the
map()method to get a new array where each element is converted to a number.