user137717
user137717

Reputation: 2165

splice not removing elements when called in a loop

I am writing a code which takes an input string and an array of markers and removes everything from the markers to the end of the on which it is found. I have a function which identifies a marker and then finds the end of the line it is on. This function returns an array where each pair of elements, starting with 0, corresponds to a section I would like to splice. However, only some of my calls to splice are actually removing anything.

Here is my main code:

function solution(input, markers){
  var positions = identify(input, markers);
  var arr = input.split('');

  for(var i = 0; i<positions.length; i+=2){
    arr.splice(positions[i], positions[i+1] - positions[i]);
    console.log(positions[i+1]);
  }
  return arr.join('');
}

I have tested identify and it is returning what I expect. This is the test I am currently failing:

Test.assertEquals(solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"]), "apples, pears\ngrapes\nbananas")

The result of my call to identify() is [14,27,43,50] and I have tried splicing with (43, 7) directly which works, so I can't figure out why it's not removing any elements while being used in the loop. I always get this as a result:

Expected: apples, pears grapes bananas

instead got: apples, pears grapes bananas !apples

Upvotes: 0

Views: 672

Answers (1)

Barmar
Barmar

Reputation: 781731

You need to work backwards through the positions array, because when you splice out some elements of arr, the indexes of everything after those elements change.

function solution(input, markers){
  var positions = identify(input, markers);
  var arr = input.split('');

  for(var i = positions.length-2; i >= 0; i-=2){
    arr.splice(positions[i], positions[i+1] - positions[i]);
    console.log(positions[i+1]);
  }
  return arr.join('');
}

Upvotes: 3

Related Questions