How to Filter Numbers from an Array in JavaScript
In this tutorial, we are going to learn about how to filter or extract the numbers from an array in JavaScript with the help of examples.
Consider, we have a following array in our JavaScript code:
const arr = [2, 3, 4, 'total', 5, 'price'];
Now, we need to filter out only numbers from the above array like this [2, 3, 4, 5]
To filter a numbers from an array, we can use the built in Array.filter() method by checking the type of an elements from the array using the ‘typeof’ operator.
The typeof operator returns the data type of the given value.
Here is an example:
const arr = [2, 3, 4, 'total', 5, 'price'];
const filterNumbers = arr.filter(el => typeof el === 'number');
console.log(filterNumbers);
[2, 3, 4, 5];
In the example above, inside the filter method we are checking the type of the element in the array is number or not , if it’s number then it will be added to an new array.
The filter method returns a new array with the values that passes the test condition.
Filtering the string numbers from an array
Sometimes, if an array contains a string numbers, first we need to convert the string numbers to a number data type then filter the numbers from an array.
Here is an example:
const arr = ['2', '3', '4', 'total', '5', 'price'];
const stringNumbers = arr.filter(el => Number(el));
const filteredNumbers = stringNumbers.map(el => Number(el));
console.log(filteredNumbers);
Output:
[2, 3, 4, 5]
In the example above, first we accessed the string numbers from an array using the filter method, then we have converted the string numbers to a data type numbers using the map() method.
The Number() constructor method takes the string number as an argument and returns a number.