How do I remove an item[i] from items once it reaches in:
$.each(items, function(i) {
// how to remove this from items
});
Although I would typically prefer using $.grep() to filter the array, I have an instance where I'm already using $.each() on the array to process a dataset. After doing some processing, I can determine whether or not the item needs to be removed from the array:
// WARNING - DON'T DO THIS:
$.each(someArray, function(index, item) {
// Some logic here, using 'item'
if (removeItem) {
// Spice this item from the array
someArray.splice(index, 1)
}
// More logic here
});
WARNING: This presents a new problem! Once the item has been spliced from the array, jQuery will still loop for the length of the original array. E.g.:
var foo = [1,2,3,4,5];
$.each(foo, function(i, item) {
console.log(i + ' -- ' + item);
if (i == 3){
foo.splice(i, 1);
}
});
Will output:
0 -- 1
1 -- 2
2 -- 3
3 -- 4
4 -- undefined
And foo is now [1, 2, 3, 5]. Every item in the array is "shifted" relative to the jQuery loop, and we missed the element "5" altogether, and the last item in the loop is undefined. The best way to solve this is to use a reverse for loop (going from arr.length - 1 to 0).
This will ensure that removing an element won't affect the next item in the loop. However since the question here is with respect to $.each, there are a few alternative ways of solving this:
1) $.grep() the array before looping
var someArray = $.grep(someArray, function(item) {
// Some logic here, using 'item'
return removeItem == false;
});
$.each(someArray, function(index, item) {
// More logic here
});
2) Push items into another array
var choiceArray = [ ];
$.each(someArray, function(index, item) {
// Some logic here, using 'item'
if (removeItem) {
// break out of this iteration and continue
return true;
}
// More logic here
// Push good items into the new array
choiceArray.push(item);
});