Iterate Through All an Array

Iterate Through All an Array
0.0 0

#1

I used this simple algorithm, for getting through this challenge. Though i was trying it, and i was pretty sure it’s not gonna work.
The reason is if arr[i] equal a number. like in the one of the test case. and i am trying to access indexOf function of arr[i] which happens to be a number. isn’t that supposed to throw an error ?

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) < 0){
      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

Hi hbadr,

 if (arr[i].indexOf(elem) < 0)

Means if elem wasn’t able to match any values in an array. It will have an index of -1. Thus, satisfying the conditional to push the array into a new array.

If elem matches to any value, (in the test case the index could only be 0, 1 or 2) it will not push the array to a new array.

arr[i].indexOf(elem)

This means look for (return) the index of the given number, elem, if it exists in the array.


#3

Hi clarkngo,
what I trying to understand is let

arr = [[1,2,true],[3,4,false],5];

Now the condition at i = 2 is supposed to throw an erro, for arr[2] = 5


#4

hi ,badr , in the challenge they wanted from you to don’t let any array contains the elem in it so to do that you have to create a loop , you have created it but the condition you have put is not correct you have to do it like this if(something.index0f===-1){ some code}
means that this thing is not existed so you can push it to the array provided in the challenge I hope this helps .


#5

Hi hbadr,

filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));

In this example, you are passing 1 array (2d array) and a number in the filteredArray function.
filteredArray(arr, elem)

Same as this:
filteredArray([[1,2,true],[3,4,false],5]);
In this example, the first parameter is a 2d array, and the second parameter is a number.

But if your example is:
let arr = [[1,2,true],[3,4,false],5];
Which is a single 2d-array, you have to access the index of number 5 and use it to filter the array[0] and array[1] of the 2d array.