简体   繁体   中英

Is it possible to manipulate the index parameter of Array.prototype.map()?

I was wondering if it is possible to do a "index--" after deleting an element in an Array while using the map function.

example:

arr.map((item, index) => item >= a && item <= b? item : arr.splice(index, 1));

after deleting the element at the said index, the index needs to be "index - 1" for the next iteration. is it possible to somehow manipulate the index in the map function?

Not in any elegant way. The better option would be to avoid splice entirely, and instead use the new returned array from the an array method only, discarding the old one.

If you want to remove items between a and b , use .filter :

const itemsNotBetweenAAndB = arr.map(item => item >= a || item <= b);

If you had to use splice to mutate the existing array (which I'd recommend against since it's ugly and impure), use a for loop:

for (let i = arr.length - 1; i >= 0; i--) {
  if (arr[i] > a && arr[i] < b) {
    arr.splice(i, 1);
  }
}

.map should be used only for creating a new array based on transforming all elements of the original array. Since here, it looks like you want to remove elements from the original array without transforming each item, .map isn't appropriate, since it won't help you accomplish the goal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM