[How to iterate through an array and delete items without breaking the For loop]

How to iterate through an array and remove items without breaking the For loop

foreword

We know that the splice() method can be used to include removing an element, adding, replacing, etc. However, the array is being re-indexed when you run splice(), which means you will skip an index when you delete it.
First, let's take a good look at how the splice() method works.

The splice() Method

The splice() method can modify the contents of an array by removing or replacing existing elements or adding new elements. Although it mutates the original array in-place, it still returns a list with the removed items. Returns an empty array if there are no deleted arrays.
js代码片断.

const anyFish= ["angel", "drum", "mandarin", "sturgeon"];
/*Remove 1 element at index 2*/
const removed = anyFish.splice(2, 1);

/*  anyFish is ["angel", "drum", "sturgeon"] */
/* removed is ["mandarin"] */

Let's start our example now and look at the problem. If we run the code snippet and look at the results, we'll see that 3 is still in the array, which is exactly the problem we mentioned above:
show some below 内联代码片.

let elements = [1, 3, 3, 5, 3, 1, 4];
let removeEl = 3;
let index = elements.indexOf(removeEl);
// we continue this till we find the element in the array
// indexOf will return the first index of the element in the array; -1 if not found
while (index !== -1) {
  elements.splice(index, 1);
// we get the new index after splice()
  index = elements.indexOf(removeEl);
}
console.log(elements);
  • The result of running the code is as follows:
> Array [ 1, 5, 1, 4 ]

This will prevent reindexing from affecting the next item in the iteration, since indexing only affects items from the current point to the end of the array. In an iteration, the next item is below the current point.

Or we can start a reverse loop:
some are shown below 内联代码片.

let elements = [1, 3, 8, 5, 16, 1, 4];
// here, we start iterating from the last element to the first one (reverse)
for (i = elements.length - 1; i >= 0; --i) {
  if (elements[i] % 2 === 0) {
    elements.splice(i, 1); // Remove even numbers
  }
}
console.log(elements);
  • The result of running the code is as follows:
> Array [ 1, 3, 5, 1 ]

Let's do it more elegantly!

Some are shown below 内联代码片.

let elements = [1, 3, 3, 5, 3, 1, 4];
// filter方法中的元素将表示每次迭代中的每个数组元素
// 在这里,如果元素不等于3,它将保留在结果数组中
const result = elements.filter((element) => element != 3)
console.log(result)
  • The result of running the code is as follows:
> Array [ 1, 5, 1, 4 ]

Guess you like

Origin blog.csdn.net/weixin_43727933/article/details/128765530