I wrote a piece of code which removes elements from an array while iterating it.
func_name: function (elementsArray) {
var orig_Array = [10,20,30,40];
for(var i=0; i < orig_Array.length; i++) {
if(elementsArray.indexOf(orig_Array[i]) > -1) {
orig_Array.splice(i, 1);
i--;
}
}
}
Which is working perfectly fine, But when I sent for review, My reviewer said that manipulating an array while iterating it is a dangerous practice, which in other languages like java leads to concurrentModificationException.
So he suggested me two ways for the above requirement. 1.) Store the elements which I don't want to delete, in a temporary array, and then re-assign the original array with temporary array, here is the code I implemented for this.
func_name: function (elementsArray) {
var tempArray = [];
var orig_array = [10,20,30,40,50];
orig_array.forEach(function (element) {
if (elementsArray.indexOf(element) > -1) {
tempArray.push(element);
}
});
orig_array = tempArray;
}
2.) Store the indexes of the elements which I want to delete from the original array, then iterate the indexesArray in reverse order and remove the elements from the original array using splice, here is the code I implemented for the second approach.
func_name: function (elementsArray) {
var indexesArray = [];
var orig_array = [10,20,30,40,50];
orig_array.forEach(function(element, index) {
if(elementsArray.indexOf(element) > -1){
indexesArray.push(index);
}
});
}
for (var i = indexesArray.length; i >= 0; i--) {
orig_array.splice(i, 1);
}
Can someone please suggest which is the best way to proceed, and also suggest if there is any other best way to achieve it.
filtermethod instead of iterating