Iterate Through All an Arrays Items Using For Loops :)

Tell us what’s happening:
So here’s my thinking, of course it’s not working. would like some elucidation on whether I’m at least in the ballpark, and if so what am I not considering. thank you.

Your code so far


function filteredArray(arr, elem) {
    let newArr = [];
    // change code below this line
  for (let i=0;i<arr.length;i++)
    if (arr.indexOf(elem) > 0){
    newArr = arr.splice(arr.indexOf(elem));
    }
    // 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));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

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

mmm, I’m thinking foul ball right now…

you’re given ‘arr’ which is actually an array of arrays.
What that means is that when you say:

arr.indexOf(elem)
you’re asking if ‘elem’ is one of the elements in the array but that is unlikely since most of the elements are themselves arrays.

For eg. if you look at the given call to filteredArray:
filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)

the ‘arr’ has 4 elements only and they are:
[3,2,3]
[1.6,3]
[3.13.26]
[19,3,9]

so obviously none of these match elem (3).

Does the above help you see what you might be missing?

In this line, you are missing out on the possibility that the element we want to be filtered out is in the 0th index of the array.

Remember the splice() command takes two arguments: the index of the item we want to get rid of in the array, and the number of elements we want removed in the array.

Keep in mind what the problem is giving you and what it is asking for. Its giving a 2-dimensional array; a list within a list, we’ll call this a “sub-list”. And it is asking for that same 2-dimensional array, but omit the sub-list that contains the filtered value in question. I didn’t realize this until 30 minutes in, when I was trying to filter out and remove just the elem in question and not the entire sub-list.

Taken from one of the test cases from the problem, but reformatted to illustrate what the problem is asking for

 filteredArray(
[[10, 8, 3], 
 [14, 6, 23], 
 [3, 18, 6]],  
**18**)

should return

[ [10, 8, 3], 
[14, 6, 23] ]