4

Is there a good functional style way of deleting elements in a JS array while looping?

I know filter can be used to create a new array:

var newArr = arr.filter((x) => x.foo > bar)

But is there a way to actually delete the elements from arr as you go?

BTW: I can't reassign, this is a data object on Vue component, so I need to update, not reassign.

BTW2: This is not a duplicate. I know how to do it with normal JS iteration. I am looking for a functional way, and the referenced answer doesn't contain that. Not a dupe.

10
  • 2
    arr = arr.filter((x) => x.foo > bar) ?? Commented Jun 10, 2018 at 15:46
  • @Chiller that still creates a new array. Commented Jun 10, 2018 at 15:47
  • The only way I know of deleting items is looping backwards over the array, or using reduce to create a new array. Commented Jun 10, 2018 at 15:47
  • Is this because of concerns about memory consumption? Commented Jun 10, 2018 at 15:47
  • 1
    @mtyson I have this same question.. did you figure out a solution as elegant as what you'd probably hoped for? Commented Feb 25, 2021 at 3:16

2 Answers 2

5

Simply re-assign the Array

let arr = [1,2,3,4,5];
arr = arr.filter(v => v < 3);
console.log(arr);

If you can't re-assign, use a loop and Array.splice. Note that for every deleted item, the index should be decremented by 1.

const arr = [1,2,3,4,5];
for (let i = 0; i < arr.length; i += 1) {
  if (arr[i] < 3) {
    arr.splice(i, 1);
    // you should decrement the index (i) now
    i -= 1;
  }
}

console.log(arr);

Sign up to request clarification or add additional context in comments.

4 Comments

I can't reassign, this is a data object on Vue component, so I need to update, not reassign.
This does not the answer of doing the filtering without re-assiging to the variable.
@fstamour now it does.
@KooiInc thanks :P (I made a small edit let -> const)
1

Why not simply do this

arr = arr.filter((x) => x.foo > bar)

UPDATE:

We can splice the unwanted item from the array while iterating, if you do not want to re-assign. Does this answer your question?

for(let i = 0; i < arr.length; i++) {
    if (arr[i].x > bar) arr.splice(idx, 1);
}

1 Comment

This does not the answer of doing the filtering without re-assiging to the variable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.