0

I have an array INTERVALS and I want to remove a subset of elements from this array. I tried using for loop and splice, but it is not working as desired. It seems the for loop should not modify the array. Any help?

function remove_intervals(list) {
  for(i=0; i < INTERVALS.length; i++) {
    var o = INTERVALS[i];
    if(o in list) {
      clearInterval(o);
      INTERVALS.splice(i,1);
    }
  }
}
5
  • 2
    It is typically an anti-pattern to iterate over an array that you are modifying inside the iteration Commented May 19, 2020 at 22:31
  • Ah looks the indexing is somehow the issue.. Any alternative? @Taplar Commented May 19, 2020 at 22:33
  • 2
    Consider a usage of filter. Or consider iterating backwards, from the end to the beginning. Commented May 19, 2020 at 22:34
  • 1
    Oh iterating backwards doesn't disturb the indexing for splice. You're truely awesome! Thank you:) @Taplar Commented May 19, 2020 at 22:37
  • 2
    Iterating backwards does change the index, but not in a manner that you care, as it does not change the preceeding index that you will continue to process on. The index after that point will change, but you don't care. You've already processed past them Commented May 19, 2020 at 22:39

2 Answers 2

2

You can use Array.prototype.filter like this:

function remove_intervals(list) {
    INTERVALS = INTERVALS.filter(id => {
        if (id in list) {
            clearInterval(id);
            return false;
        }

        return true;
    });
}
Sign up to request clarification or add additional context in comments.

Comments

1

Could you do this using a the filter and inccludes methods to create a new array

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const toRemove = ['limit', 'elite', 'destruction'];

const result = words.filter(word => toRemove.includes(word));

console.log(result);
// expected output: Array ['spray', 'exuberant', 'present'];

2 Comments

Also, in operator looks for the property name, not for a value in an array.
Ah, I see what you're trying to do now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.