Remove array elements while iterating in JavaScript
This post will discuss how to remove elements from an array while iterating over it in JavaScript. The solution deletes elements based on a condition and shift the remaining elements to the left.
Removing elements from an array while iterating over it can be tricky, because the array length and indices may change as we remove the elements. There are a few ways to avoid this problem, such as:
1. Looping backwards
Loop backwards with a decrementing index is a common technique that works in any version of JavaScript. It involves using a for loop to iterate over the array from the end to the beginning, and using the splice() function to remove the element at the current index if it meets a certain condition. For example, if we have an array [1, 2, 3, 4, 5] and we want to remove all the odd elements, we can do:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
var arr = [1, 2, 3, 4, 5]; for (var i = arr.length - 1; i >= 0; i--) { // check if the element is odd if (arr[i] % 2 !== 0) { // remove one element at the current index arr.splice(i, 1); } } console.log(arr); // [2, 4] |
We loop backwards to avoid array re-indexing affect the next element in the iteration. This way it only affects the elements from the current index to the end of the array. If we use a for loop with an incrementing index and the splice() function to remove elements, we may end up skipping some elements or going beyond the bounds of the array. This is because the splice() function changes the length and the indexes of the array, which affects the loop condition and the current index.
2. Using filter() function
The Array.filter() function creates a new array with all elements that pass a test implemented by a provided function, and optionally assigning it back to the original array. This function does not modify the original array, but returns a new one. The advantage of this approach is that we can iterate over and filter out some elements from an array without modifying it. For example, if we have an array [1, 2, 3, 4, 5] and we want to create a new array without even elements, we can do:
|
1 2 3 4 5 6 7 |
var arr = [1, 2, 3, 4, 5]; // create a copy of the original array without all the even elements var newArr = arr.filter(item => item % 2 !== 0); console.log(arr); // [1, 2, 3, 4, 5] console.log(newArr); // [1, 3, 5] |
That’s all about removing elements from an array while iterating over it in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)