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.

Robycool
  • 1,104
  • 2
  • 14
  • 26
  • 1
    Typescript is a superset of JS. It should work. – vibhor1997a Jul 10 '18 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. – A. Llorente Jul 10 '18 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. – Robycool Jul 10 '18 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. – A. Llorente Jul 10 '18 at 13:18

1 Answers1

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.

A. Llorente
  • 1,142
  • 6
  • 16
  • from the [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) 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). – Robycool Jul 10 '18 at 13:56
  • 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 – A. Llorente Jul 10 '18 at 13:59