Filter An Array To Only Numbers In JavaScript

To filter an array to only numbers in JavaScript, you can use the Array.filter() method and check if type of each element is number.

How To Filter An Array To Only Numbers In JavaScript

The following example shows how to filter an array to only numbers in JavaScript.

//Input Array

var input = [-1, 0, "hello", 1, 2, 3, [1]];

//Filter Function

function isNumber(x) { return typeof x === 'number'; }

//Output Array

var output = input.filter(isNumber);

console.log(output);

//Output: [-1, 0, 1, 2, 3]

As you can see from the output, the isNumber() function returns true if an element is of type number and false otherwise. The Array.filter() method then creates a new array with only those elements for which the function returned true.

You can also use the isNaN() function to filter an array to only numbers in JavaScript. The isNaN() function returns true if a value is not a number and false otherwise.

The following example shows how to use the isNaN() function to filter an array to only numbers in JavaScript.

//Input Array

var input = [-1, 0, "hello", 1, 2, 3, NaN];

//Filter Function

function isNumber(x) { return !isNaN(x); }

//Output Array

var output = input.filter(isNumber);

console.log(output);

//Output: [-1, 0, 1, 2, 3]

As you can see from the output, the isNaN() function returns true for all values except numbers. The Array.filter() method then creates a new array with only those elements for which the function returned true, i.e., for all numbers.

You can also use the Number() function to filter an array to only numbers in JavaScript. The Number() function returns the numeric value of a value.

The following example shows how to use the Number() function to filter an array to only numbers in JavaScript.

//Input Array

var input = [-1, 0, "hello", 1, 2, 3];

//Output Array

var output = input.filter(Number);

console.log(output);

//Output: [-1, 1, 2, 3]

As you can see from the output, the Number() function returns the numeric value of a value. The Array.filter() method then creates a new array with only those elements for which the function returned a number, i.e., for all numbers.

The problem here is that 0 is a falsy value in JavaScript, so it will not be included if you use the Number() function.

If you want to include 0 in the output array, you can use the above two methods.

Conclusion

In this article, you learned how to filter an array to only numbers in JavaScript. You can use the Array.filter() method with a function that checks if each element is of type number or use the isNaN() or Number() function.

how to filter an array to only numbers in JavaScript

Leave a Reply