var results = ['one', 'two', 'one hundred', 'three'];
var removal = [];
$.each(results, function(i) {
removal.push(i);
if (results[i].indexOf('one') == -1){
console.log('Removing:' + results[i] + '(' + removal[i] + ')');
results = results.splice(removal[i], 1);
}
});
I have the following code, but it is breaking after it removes the first result.
I want it to remove anything that does not contain the word ‘one’.
I am guessing it is breaking because the removal order changes once one has been removed.
What am I doing wrong?
You shouldn’t splice the Array while you’re iterating it with
$.each().Since you’re changing the length of the Array, you’re going beyond the final index since.
Just use a
forloop and adjustiwhen you remove an item…Note that I changed this…
to this…
You don’t want that since
splice()modifies the original, and returns the item(s) removed.