0

I just did a coding challenge where I had to remove all non numberic items from an array without creating a new array which means no map or filter.

I didn't do that great because I was trying to splice but I'd lose my index.

What is a nice way of doing this?

const filterNums = (nums) => {
  for (let item in nums) {
    if (typeof nums[item] !== 'number') {
      // Remove item
    }
  }
  return nums;
};

console.log(filterNums([1, 'a', 2, 'b', true]));
nandesuka
  • 699
  • 8
  • 22
  • See also [Find and remove all non numbers from array in JavaScript w/out JQuery](https://stackoverflow.com/q/58279146/215552), [Returning only numbers and removing strings from existing array in javascript?](https://stackoverflow.com/q/53037092/215552), [Javascript/jQuery: remove all non-numeric values from array](https://stackoverflow.com/q/24022682/215552), etc. – Heretic Monkey May 19 '21 at 22:58

1 Answers1

1

Use an indexed-based loop instead, starting at the end of the array.

const filterNums = (nums) => {
  for (let i = nums.length - 1; i >= 0; i--) {
    if (typeof nums[i] !== 'number') {
      nums.splice(i, 1);
    }
  }
  return nums;
};

console.log(filterNums([1, 'a', 2, 'b', true]));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320