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']
0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You need to decrement i by 1 after splicing when iterating forward.
@nibble Indeed, that's an alternative: when iterating forward, call array.splice(i--, 1);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.