1

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 ...

  • 3
    You’re mutating an array as you iterate it, but never adjust the index. Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and use the available static and instance methods of [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Aug 23 '21 at 00:29

3 Answers3

4

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));
coding monster
  • 384
  • 4
  • 18
1

Global newArray.

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

Here is filterArr function, parameter is same.

let result = [];
for (let item of newArr){
    for (let i = 0; i< item.length; i++){
        if (item[i] == elemn){
            item.splice(i, 1);
            i--;
        }
    }
     result.push(item);
}

return result;

You can call filterArr function and show same result as you expect.

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

As metioned in the comments, you might check out the javascript Array class. There is a built in filter method which might simplify this a bit.

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

function filterArray(arr, valueToFilter) {
   return arr.map( (subArray) => subArray.filter( (value) => value !== valueToFilter ) );
}

console.log(filterArray(newArr,4));
mr rogers
  • 3,200
  • 1
  • 19
  • 31