Iterate Through All an Array's Items Using For Loops why is my solution not working?

Tell us what’s happening:
So if my arr[i] value is NOT equal to elem which in this example is 3, then it should push that value into newArr. This should be working, I think it should, but it’s not :expressionless: why? I’ve read up to hint number two and it says to use indexOf, but I don’t know, I can’t get over why this isn’t working.

EDIT
So I read it again and it seems I need to remove the whole array that has elem in it, but if possible I would still like to know what’s wrong with my code. I should be getting a new array with NO elem in it, but it’s not happening.

Your code so far


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

You are only looping through the subarrays of the arr, not elements inside subarrays.

The variable i is not defined in your code.

1 Like

Let’s first understand this -
function fiteredArray is being passed the following two params which when coupled with functions arguments will look like:

arr = [[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]] 
elem = 3

The issue:
When the loop begins - the first value of i is 0

In the first pass,
arr[i] is [3,2,3]
elem is 3

since, ([3,2,3] !== 3) this expression will always be true.

as, Arrays are not equal to Number in JavaScript.

[3,2,3] will be pushed to newArr along with [1, 6, 3], [3, 13, 26] & [19, 3, 9]

Here’s what you actually wanna do:

function filteredArray(arr, elem) {
	let newArr = [];
  	// change code below this line
	for (i = 0; i < arr.length; i++) {
  		if (arr[i].includes(elem) === false){
			newArr.push(arr[i]);
		}
  	}
    // change code above this line
    return newArr;
    console.log(newArr);
}

// change code here to test different cases:
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [1, 13, 26], [19, 3, 9]], 3));

I managed to solve it earlier but also forgot to declare i as variable xD but thanks a lot for explaining it. Most of the time even when things work, I still don’t get how so explanations like yours are very helpful