Robycool
Robycool

Reputation: 1224

Typescript way to slice elements from array while looping over it

What is the typescript way to slice elements from an array while looping over all its elements? Obviously, I want to take into account that the array is re-indexed at every splice.

As stated in this post the javascript way of doing this would be:

var i = array.length
while (i--) {
    ...
    if (...) { 
        array.splice(i, 1);
    } 
}

Unfortunately, the typescript for (let item of array) {} loops from 0 to array.length-1 instead of the other way around like the js function above. Splicing an element in this loop would result in one item being skipped.

Upvotes: 1

Views: 3844

Answers (1)

A. Llorente
A. Llorente

Reputation: 1162

From what I understood from your answers what you need is to filter the array:

const filteredArray = array.filter(element => {
    if (yourConditionIsTrue) { // if this element should be in the filteredArray
        return true;
    } else {
        return false
    }
});

Which can be done in one line:

const filteredArray = array.filter(element => conditionIsTrue);

This way your array remains untouched and you get a new array (filteredArray) only with the elements you need, but you don't mess up with the array you are iterating.

Upvotes: 2

Related Questions