Search code examples
javascriptarraysloopsnestedsplice

for loop: Nested array in javaScript


My code:

let newArr = [[1,5,6,4],[8,5,4],[4,4,4,4]];

function filterArr(arr, elemn){
  for(let i = 0; i < arr.length; i++){
    for(let j=0; j < arr[i].length; j++){
        if(arr[i][j] === elemn){
        arr[i].splice(j,1);
      }
    }
  }
  return arr;
}

console.log(filterArr(newArr,4));

The Result: [[1,5,6],[8,5],[4,4]]

I am stuck at this point : [4,4] it supposed []

any suggestion plz ...


Solution

  • I'll quote some sentences from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

    deleteCount Optional
    An integer indicating the number of elements in the array to remove from start.

    If deleteCount is omitted, or if its value is equal to or larger than array.length - start (that is, if it is equal to or greater than the number of elements left in the array, starting at start), then all the elements from start to the end of the array will be deleted.

    If deleteCount is 0 or negative, no elements are removed. In this case, you should specify at least one new element (see below).

    You delete jth element and j++ so that the next of deleted element is skipped after deletion. After once deletion you should use j--.

    The full right code is as follows:

    let newArr = [[1,5,6,4],[8,5,4],[4,4,4,4]];
    
    function filterArr(arr, elemn){
      for(let i = 0; i < arr.length; i++){
        for(let j=0; j < arr[i].length; j++){
            if(arr[i][j] === elemn){
            arr[i].splice(j, 1);
            j --;
          }
        }
      }
      return arr;
    }
    
    console.log(filterArr(newArr,4));