Iterate through for loops

Iterate through for loops
0

#1

Tell us what’s happening:
I can’t seem to figure out why the second test input parameters does not passed the test, whereas all others passed. The input parameters is: filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2). The function is suppose to return [["flutes",2]], but the actual output returns [ [ ], ["flutes",2] ]. I’m out of thought here, please help.

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[i]=[...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 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 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

have you tried adding console.log statements to your code? (both in and out of the for loop and in and out of the if statement? Track your variables to see what is happening to them as the program runs.
If you want to view the console in Chrome just click CTRL-SHIFT-J


#3

Okay, does this help?
CON1 CON2


#4

So think about the logic of your for loop for a minute. You’re saying “iterate over the array arr, and when you find an array that doesn’t contain elem, place that array into newArr AT THE SAME INDEX.” So, when ["flutes", 4] is found at index position 1, it is inserted into newArr at index position 1. So what is at index position 0? Well, you told the javascript engine that newArr is an array, so it will populate newArr[0] with an empty element.

Is this, in fact, what you WANT to happen?

And yes, the console.log info does help. As @hbar1st pointed out, it can be used to track your variables within the loop, as they change. In this case, had you placed a console.log inside the loop, you’d see that newArr (in the case of the [“flutes”, 4] containing array) is unpopulated until that member is found, then newArr suddenly contains two elements.


#5

Ah Yes… It all make sense now. Thank you. Now here’s the solution:

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;

}
```[spoiler]This text will be blurred[/spoiler]

#6

Exactly. However, try not to post solutions here, as others may later encounter this. At the very least, do the spoiler blur on your actual code.