Peter Peach
Peter Peach

Reputation: 169

Why should we decrement an i variable and use break in a function?

What is the purpose of decrementing the "i" variable and using "break" in this function?

function filteredArray(arr, elem){
  let newArr = [...arr];
  for(let i = 0; i < newArr.length; i++){
    for(let j = 0; j < newArr[i].length; j++){
      if(newArr[i][j] === elem){
        newArr.splice(i, 1);
        i--;
        break;
      }
    }
  }
  return newArr;
}

console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));

Upvotes: 1

Views: 54

Answers (1)

MKougiouris
MKougiouris

Reputation: 2861

This is because by using newArr.splice(i, 1); you are removing the current index item from the array, so since all indexes will be moved by -1 for all elements following i at each splice, you then have to reduce i by 1, so you dont skip elements

Upvotes: 2

Related Questions