We often face a basic problem of iteration through an array in Javascript, but recently when i was implementing lazy load in my app, I came across a problem in which i had to delete the element parallely as i was iterating through the array, to avoid running two separate loops for both. So there are 3 approaches that i tried which i will explain below, and only one of them is a correct way to do it.
1. Running a basic for loop from i=0 to i= array.length
var dummyArr = [1,2,3,4,5,6]
for (var i=0; i< dummyArr.length; i++) {
if ( dummyArr[i] == 2 || dummyArr[i] == 3) {
dummyArr.splice(i,1);
}
}
Now this will give output as dummyArr = [1,3,4,5,6]. It skips the ‘3’ coz after splice is called the indexes in array are modified, just for starters splice is used for deleting element in array (Array Splice). So that element was skipped
2. Next approach that i tried was using forEach method ( forEach ) in JS. It also does the same thing as basic for loop, but in my conquest towards becoming a better JS dev. I try to use some new and cool things for my code to look better.
var dummyArr = [1,2,3,4,5,6]
dummyArr.forEach(function( elem, index) {
if (elem == 2 || elem == 3) {
dummyArr.splice(index,1);
}
});
So like I said it does the same thing as a basic for loop, nothing fancy. It ignores the elements that are newly appended and skips the indexes that have been deleted.
Output — dummyArr = [1,3,4,5,6]
3. Last and apt approach was running a reverse for loop through the array.
var dummyArr = [1,2,3,4,5,6]
for (var i=dummyArr.length -1; i>=0; i–) {
if ( dummyArr[i] == 2 || dummyArr[i] == 3) {
dummyArr.splice(i,1);
}
}
Output — dummyArr = [1,4,5,6]
Now in this case on deletion of element and modification of index the upcoming element’s position and value are not compromised which was happening in previous cases. So the element can be deleted as u desire it to be.
Thanks for going through the post.. Will come back with a new post soon.
Adios