[SOLVED]Help in Iterate Through All an Array's Items Using For Loops

[SOLVED]Help in Iterate Through All an Array's Items Using For Loops
0.0 0

#1

Tell us what’s happening:
Hello guys i’m stuck in this challenge, why in the last scenario ,
here >> filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)
only return false 2 times?

Your code so far


function filteredArray(arr, elem) {
  let newArr = [];
  // change code below this line
  for(var i = 0; i < arr.length; i++){
    var verify = arr[i].every(function(x){
        return (x != elem);        
    });
    if(verify == false){
      arr.splice(i,1);
    }
  }
  newArr = arr;
  // 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/66.0.3359.139 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 the first iteration, verify becomes false.
Then you use splice and delete the first element of the array => [1, 6, 3 ], [ 3, 13, 26 ], [ 19, 3, 9 ]
In the second iteration, verify becomes false, too.
Then you use splice and delete the second element of the array => [ 1, 6, 3 ], [ 19, 3, 9 ]
In the third iteration, there is no third element and you are finished.


#3

You’re on the right path, but I have to ask: If you’re going to use every() inside the loop, why not just filter() directly? This would bypass any issues you’re seeing here.


#4

Thanks for your awnser, i fix my code.
function filteredArray(arr, elem) {

let newArr = [];
// change code below this line
for(var i = 0; i < arr.length; i++){
var verify = arr[i].every(function(x){
return (x != elem);
});
if(verify == true){
newArr.push(arr[i]);
}
}

// change code above this line
return newArr;
}

// change code here to test different cases:
console.log(filteredArray([ [“amy”, “beth”, “sam”], [“dave”, “sean”, “peter”] ], “peter”));