Basic Data Structures - Iterate Through All an Array's Items Using For Loops

Tell us what’s happening:
I was so close solving this without a hint…almost.

For the if statement I originally entered:
if (arr[i].indexOf(elem) >= 0) {}
however the solution was:
if (arr[i].indexOf(elem) == -1)

I don’t understand why >= 0 would also note work? My thought is if elem is >=0 continue for loop and iterate through array.

Or is the reason it doenst work because “==” is a better use because elem could be string, number, etc and loose equality works better? If so, why -1?

Your code so far

DELETED SINCE I GOT THE SOLUTION JUST CANT UNDERSTAND A PORTION OF CODE


**Your browser information:**

User Agent is: <code>Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36</code>

**Challenge:** Basic Data Structures - Iterate Through All an Array's Items Using For Loops

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

Hello!

Unfortunately, the code was too large to post this way.

Please try posting the complete code using three back ticks ``` before and after the code?

In this way, the community can see and provide accurate guidance to help you resolve your problem with the code.

Keep up the good progress! :slight_smile:

Reposting

Tell us what’s happening:
I was so close solving this without a hint…almost.

For the if statement I originally entered:
if (arr[i].indexOf(elem) >= 0) {}
however the solution was:
if (arr[i].indexOf(elem) == -1)

I don’t understand why >= 0 would also note work? My thought is if elem is >=0 continue for loop and iterate through array.

Or is the reason it doenst work because “==” is a better use because elem could be string, number, etc and loose equality works better? If so, why -1?

  let newArr = [];
   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));```

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.