Iterate Through All an Array's Items Using For Loops: Alternate Solution?

Iterate Through All an Array's Items Using For Loops: Alternate Solution?
0

#1

Tell us what’s happening:

Hi!

I’ve been working on this challenge for a bit and after looking at the hints I understand that I was trying to do it in an unnecessarily complicated way, but I don’t understand why my current code doesn’t work. It succeeds with arrays that contain only numbers, but not with the ones that contain strings. For example, when I put in filteredArray([ [“trumpets”, 2], [“flutes”, 4], [“saxophones”, 2] ], 2), it logs flutes,4,.

Again, I now know that I should complete the challenge using .indexOf to make it simpler, but I’d just like to know what’s wrong with my current code.

Thanks!

Your code so far


function filteredArray(arr, elem) {
  let newArr = [];
  // change code below this line
  for (let i = 0; i < arr.length; i++) {
    let subArr = [];
    let elemPresent = false;
    for (let j = 0; j < arr.length; j++) {
      if (arr[i][j] != elem) {
        subArr.push(arr[i][j]);
      } else {
        elemPresent = true; 
      }
    }
    if (elemPresent != true) {
      newArr.push(subArr);
    }
  }
  // change code above this line
  return newArr;
}

// change code here to test different cases:
console.log(filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2));

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


#2

In your inner loop you should iterate over the sub-arrays.

for (let j = 0; j < arr[i].length; j++) {

That’s why you’re getting “flutes,4,”, you’re just looping too much.


#3

That makes total sense; what a difference a tiny detail can make.

It works now, thanks for your help!