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

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

#1

Tell us what’s happening:

Hey i just do not understand the instructions in this challenge.

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[i].indexOf(elem) === -1){
      newArr.push(arr[i]);
    }
  }
  // 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


#2

What type will arr[i][j] be? Will it be an array?


#3

hi Aditya

your code works perfectly but you say you don’t understand?
Can you tell us what exactly you need clarification on?


#4

Hey @hbar1st i actually copied the solution code.
The thing that i fo not get is arr.indexOf(elem)


#5

No it will not be i guess


#6

arr is an array
indexOf is a function that acts on an array

  • it takes a value parameter to look for in the array and returns the index of that value if found (or -1 if not)

#7

I just had the issue cause of nested arrays .
Now, i have got it after some reading.
Thanks.


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

Why does this console log an empty array for me? Anyone?


#9

Because that is what the code should be doing to pass the challenge. The instructions state:

Modify the function, using a for loop, to return a filtered version of the passed array such that any array nested within arr containing elem has been removed.

Since 3 is contained in each of the sub-arrays, so they all get removed from the final array (newArr). Since newArr starts as an empty array, it remains as an empty array, because no sub-arrays were pushed.


#10

Welp. I misunderstood that for days. Thank you. @randelldawson