Author -  Sai gowtham

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.

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY