Iterate through all array items using for loops

Iterate through all array items using for loops
0

#1

https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops
I came across this problem, i tried everything and couldn’t do , finally looked at hints,it was very similiar with what i i did but it had something else. here’s the solution

function filteredArray(arr, elem) {
  let newArr = [...arr];
  // change code below this line
  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);
          console.log(newArr + 'x');
        i--;
        break;
      }
    }
  }
  // change code above this line
  return newArr;
}

// change code here to test different cases:
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));

i didn’t had the " i–" line and break; , can anyone explain why do we need them?


#2

This is an invalid operation. You need to use double minus signs like this i--;


#3

When you use splice, you will skip the next item newArr unless you decrease i by one.

Assuming you have the i-- in the code, you must break out of the inner for loop, otherwise if the first sub array is spliced out , the i-- make i a -1 and the inner for loop condition of j < newArr[-1].length would error out, because there is no such -1 index of newArr. newArr[-1] is undefined and underfined does not have a length property.