1

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.

4
  • 1
    Typescript is a superset of JS. It should work. Commented Jul 10, 2018 at 12:59
  • 1
    do you have a requirement to not create a new array? The correct way (in es6) would be to filter the array, which will create a new one with the elements you want. Commented Jul 10, 2018 at 13:00
  • @A.Llorente The sliced array must remain the original array (in my case, it contains objects in a datastore). However, creating a local copy of the array and looping through that copy would allow me to splice the original array without side effects. Commented Jul 10, 2018 at 13:12
  • The question is why would you want to alter the array? You can filter the original array and return only the elements that meet your if condition. Commented Jul 10, 2018 at 13:18

1 Answer 1

2

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.

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

2 Comments

from the documentation it seems like I can just write: array = array.filter(element => yourCondition). Correct? You'll notice I keep the same reference which is in fact what I meant above (sorry for unclarity).
Yes indeed you could do it in one liner, if your function returns true the element is added, if it returns false it will not, I will update my answer because it was not clear enough

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.