Filter an Array to only Numbers in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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 element 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 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 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 used the filter method to iterate over the array. 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 wouldn't 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 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 numbers.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.