How to Filter an Array to Get Only Numbers in JavaScript
Filtering an array to extract only its numeric elements is a common data sanitization task. However, the "right" way to do it depends on what you consider a "number." Do you need only values of the strict number type, or should you include strings that can be converted to numbers (like "123")?
This guide will teach you the modern and standard methods for each of these scenarios using Array.prototype.filter(). You will learn how to perform strict type checks, how to leniently filter for numeric values, and how to specifically isolate integers.
Core Method: Array.prototype.filter()
The filter() method is the perfect tool for this job. It creates a new array containing all the elements that pass a test implemented by a provided function. The logic is simple: if the function returns true, the element is kept; if it returns false, the element is discarded.
Scenario 1: Filtering for Strict number Types
This is the most common and strictest requirement. You want to create a new array containing only the elements that are of the JavaScript number data type. This will exclude numeric strings.
For example, we have a mixed array and need to extract only the true numbers.
// Problem: How to get [1, 3] from this array?
const mixedArray = [1, 'hello', 3, null, '42', undefined];
The recommended solution uses filter() with the typeof operator to check each element's data type.
const mixedArray = [1, 'hello', 3, null, '42', undefined];
const onlyNumbers = mixedArray.filter(element => typeof element === 'number');
console.log(onlyNumbers); // Output: [1, 3]
This is the most direct and reliable way to filter for strict number types.
Scenario 2: Filtering for Numeric Values (including strings)
Sometimes you need to be more lenient and include strings that represent valid numbers. For this, we need a more robust test than typeof.
For example, we have an array with mixed types and want to extract both numbers and numeric strings.
// Problem: How to get [1, '42', 0] from this array?
const lenientArray = [1, 'hello', null, '42', '', 0];
The best approach is to use filter() to check that the value is not empty and is not NaN (Not-a-Number), and then use map() to convert the filtered results into number types.
const lenientArray = [1, 'hello', null, '42', '', 0];
// Step 1: Filter out non-numeric and empty strings
const filtered = lenientArray.filter(item => {
// A robust check for numeric values
return item !== null && item !== '' && !isNaN(Number(item));
});
// At this point, `filtered` is [1, '42', 0]
// Step 2: Convert the filtered strings to numbers
const numericValues = filtered.map(Number);
console.log(numericValues); // Output: [1, 42, 0]
Why the complex filter? A simple !isNaN(item) check is not enough, as !isNaN('') and !isNaN(null) both incorrectly evaluate to true. The check item.trim() !== '' is also a good addition to handle strings containing only whitespace.
Scenario 3: Filtering for Integers Only
If you need to be even more specific and extract only whole numbers (integers), the Number.isInteger() method is the perfect tool.
Important: Number.isInteger() is a strict check. It does not perform type coercion and will return false for numeric strings.
For example, we have an array of numbers and want to extract only the integers.
// Problem: How to get [6, 5, 14, 0] from this array?
const numberArray = [1.1, 6, 5, 14.0, 0, 3.14];
The solution is that you can pass the Number.isInteger method directly to filter().
const numberArray = [1.1, 6, 'test', 5, 14.0, 0, 3.14];
const integersOnly = numberArray.filter(Number.isInteger);
console.log(integersOnly); // Output: [ 6, 5, 14, 0 ]
This is a very clean and readable way to isolate integers from an array of numbers.
Conclusion
The filter() method is a powerful tool for creating a new array containing only numbers, but it's crucial to choose the right test for your specific needs.
- To filter for strict
numbertypes, usetypeof element === 'number'. This is the most common and safest approach. - To filter for numeric values (including strings), use a robust
filter()condition to remove non-numeric values, then chain a.map(Number)to convert the results. - To filter for integers only, use
Number.isInteger. Remember that this is a strict check and will not work on numeric strings.