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']
The easier way to go about it would be to use
filter()to create a filtered copy of the array:If you insist on modifying the array in place with
splice():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.