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.
2 Answers 2
You can use Array's filter method instead of iterating:
func_name: function (elementsArray) {
var orig_Array = [10,20,30,40];
orig_Array = orig_Array.filter(function(el) {
return elementsArray.indexOf(el) < 0;
});
}
Comments
This is how I'd usually always delete an item from an array. It's as simple as this, you can then add a loop.
var testArray = ["12","13","14","15"];
var indexItem = testArray.indexOf("14");
if (indexItem >= 0) {
arr.splice( indexItem, 1 );
console.log(testArray);
}
Loop
Array.prototype.deleteItem = function(val) {
var indexItem = this.indexOf(val);
if (indexItem >= 0) this.splice(indexItem, 1);
return this;
};
var testArray = ["12","13","14","15"];
var newTestArray = testArray.deleteItem("14");
console.log(newTestArray);
Also as hindmost said you can use Array's filter method instead of iterating
func_name: function (elementsArray) { var orig_Array = [10,20,30,40]; orig_Array = orig_Array.filter(function(el) { return elementsArray.indexOf(el) < 0; }); }
filtermethod instead of iterating