I don’t see why i can’t get 4th check and my answer is 1,6,3,19,3,9 instead of empty array. I see pattern that only arrays with first number matched with element was deleted but i used indexOf method so i didn’t expect that. Can you give me a clue?
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) {
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));
for (let i = 0; i < arr.length; i++) {
...
arr.splice(i, 1);
...
You are taking elements from the array while you’re looping through it. The last test doesn’t pass because after the second iteration, the arr contains only two elements and i is already 2, so i < arr.length doesn’t pass and you break out of the loop.
To solve this I’d invert your logic, instead of checking if the element exists in the array and then removing the sub-array, I’d check if the element doesn’t exist in the array like arr[i].indexOf(elem) === -1 and then push the sub-array into newArr.