Iterate Through All Items Using For Loops

Iterate Through All Items Using For Loops
0.0 0

#1

Tell us what’s happening:

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)>-1){
      arr[i].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 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 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

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

From:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

So maybe there is a problem when the array has repeated elements. I think your code only delete one item.


#3

function filteredArray(arr, elem) {
let newArr = [];
// change code below this line
for(let i =0; i<arr.length ; i++){

if(arr[i].indexOf(elem)>-1){
  arr[i].splice(i,1);
  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));

i edit this .


#4

Did you execute that code?


#5

still not running…not passed the testcase


#6

filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18) should return [ [10, 8, 3], [14, 6, 23] ]
filteredArray([ [“trumpets”, 2], [“flutes”, 4], [“saxophones”, 2] ], 2) should return [ [“flutes”, 4] ]
these are testcases


#7

If the item of arr is also an array you need to delete all the occurrences of elem, maybe use another loop through the array.


#8

oh it worked now. i fixed it . just figured it out. thanks


#9

function filteredArray(arr, elem) {
let newArr = [];
// change code below this line
for(let i =0; i<arr.length ; i++){

if(arr[i].indexOf(elem)>-1){
  arr.splice(i,1);
  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));
this worked