• Home
  • How to filter out only Numbers in an Array using JavaScript

How to filter out only Numbers in an Array using JavaScript

To filter out only numbers from an array in JavaScript, you can use the Array.prototype.filter() method. This method takes a callback function as an argument, which is applied to each element in the array. If the callback function returns true, the element is included in the resulting array, otherwise it is excluded.

Here is an example of using the filter() method to remove non-numeric elements from an array:

const arr = [1, 2, 'a', 3, 4, 'b', 5];

const result = arr.filter(element => {
// Check if the element is a number
return typeof element === 'number';
});

console.log(result); // Output: [1, 2, 3, 4, 5]

Note that the filter() method does not modify the original array, but rather creates a new array with the filtered elements. If you want to modify the original array, you can use the Array.prototype.forEach() method or a for loop to iterate through the array and remove non-numeric elements directly.

arr.forEach((element, index) => {
if (typeof element !== 'number') {
arr.splice(index, 1);
}
});

console.log(arr); // Output: [1, 2, 3, 4, 5]

 

for (let i = 0; i < arr.length; i++) {
if (typeof arr[i] !== 'number') {
arr.splice(i, 1);
i--;
}
}

console.log(arr); // Output: [1, 2, 3, 4, 5]