jdmac
jdmac

Reputation: 43

Redefine array using itself

I wrote this solution to a problem I had, but I don't feel entirely comfortable with it. It seems to be dangerous, or at least in bad practice to use an array to redefine itself, sort of like trying to define a word but using the word in the definition. Can anyone explain either why this is wrong, or why it's ok?

let array = []

// other stuff happens to fill the array

array = array.filter(element => element !== true)

The reason I'm doing it this way is that I need that same variable name (array, for these purposes) to remain consistent throughout the function. The contents of the array might be added or removed multiple times before the array gets returned, depending on other behavior happening around it.

Let me know if this is too vague, I'll try to clarify. Thanks!

Upvotes: 1

Views: 347

Answers (2)

Steven Spungin
Steven Spungin

Reputation: 29149

You can loop through your array backwards and remove the items, as to not allocate another array and reassign.

for (i = array.length - 1; i >= 0; --i) {
  if (!!array[i]) {
    array.splice(i, 1);
  }
}

This solution is:

  1. Fast
  2. Memory efficient
  3. Will not interfere with any other code that has a reference to your original array.

Upvotes: 0

Amit
Amit

Reputation: 4353

It's perfectly fine. The right side (array.filter(element => element !== true)) of the assignment will be evaluated first, generate a completely new array and only then it'll be assigned back into array.

Upvotes: 1

Related Questions