Iterate Through All an Array's Items Using For Loops Filter Array

Iterate Through All an Array's Items Using For Loops Filter Array
0

#1

Tell us what’s happening:
I’m stuck solving this problem. My code passes all the tests except for the first one. It should return [ [10, 8, 3], [14, 6, 23] ], but it doesn’t do that. It passes only the first sub-array( [10, 8, 3]), but it does not pass the second sub-array ([14, 6, 23] ). Please help…

Your code so far


function filteredArray(arr, elem) {
  let newArr = [];
  // change code below this line
  for(let i = 0; i < arr.length; i++){
    let index = arr[i].indexOf(elem);
    if (index == -1) {
      arr.splice(index, 1);
      newArr.push(arr[i]);
    }
  }
  // change code above this line
  return newArr;
}

// change code here to test different cases:
console.log(filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops/


#2

Why are you using splice on arr?


#3

I have tried different ways to use splice. I have tried arr[i].splice, but that filters numbers inside the sub-arrays and not the sub-array itself.


#4

Comment out that splice line and see what happens.


#5

Okay I got it. I erase the splice and push arr[i] onto newArr. Thanks


#6

Since you know if index is equal to -1, that elem was not found in arr[i], you know you can add it to newArr.