Filter an Array to only Numbers in JavaScript

avatar

Borislav Hadzhiev

Sat Nov 13 20212 min read

banner

Photo by Henry Lai

Filter an Array to only Numbers in JavaScript #

Use the 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 number.

index.js
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 that the filter() method returns.

On each iteration, we check if the element has a type of number using the typeof operator.

The typeof operator 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 filter method.

index.js
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.

The 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.

The falsy values in JavaScript are: null, undefined, false, 0, "" (empty string), NaN (not a number).

The filter() method would return the valid numbers as is, but we can use themap() method to get a new array where each element is converted to a number.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee