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

1

3 Answers 3

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));

Sign up to request clarification or add additional context in comments.

3 Comments

before adding j-- there was a problem..now it is ok
@AbdulhameedSabur, yup, the first time i wrote, i didn't have read your question more deeply
You are awesome
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));

Comments

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));

1 Comment

You are right.. But I want it with for loop 👌

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.