0

I am trying to iterate over an array of strings with a "mistake" element that needs to be spliced. How can I utilize the array.splice() method to remove that item, in this case a typeof "number" within an array of strings? The below code returns the original array with the 'number' still present.

var inputFunction = function filterOutNumbers(array) {
  // iterate over input array
  for (var i = 0; i < array.length; i++) {
    // if type of current value is not equal to string, delete current value
    if (typeof array[i] !== 'string') {
      array.splice(array[i]);
    }
    }
  return array;
}

var inputArray = ['only', 'words', 'go', 'in', 78, 'here']
var output = inputFunction(inputArray);
console.log(output); // should log ['only', 'words', 'go', 'in', 'here']
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156

1 Answers1

1

The easier way to go about it would be to use filter() to create a filtered copy of the array:

const array = ['only', 'words', 'go', 'in', 78, 'here'];

const result = array.filter(v => typeof v === 'string');

console.log(result);

If you insist on modifying the array in place with splice():

const array = ['only', 'words', 'go', 'in', 78, 'here'];

for (let i = array.length - 1; i >= 0; i--) {
  if (typeof array[i] !== 'string') array.splice(i, 1);
}

console.log(array);

It's important here to iterate in reverse. If you iterate forward, the index values will no longer match once you splice the array, resulting in elements being skipped.

Also look at the documentation for splice(). The usage in your original code is incorrect.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156