The logic seems good so why is it not working. What am i missing?
Your code so far
function filteredArray(arr, elem) {
let newArr = [];
// change code below this line
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
if (arr[i][j] !== elem) {
newArr.push(arr[i]);
}
}
}
// change code above this line
return newArr;
}
// change code here to test different cases:
console.log(filteredArray([[3, 2, 3], [1, 6, 4], [3, 13, 26], [19, 3, 9]], 3));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0.
The issue is that the only way a subarray won’t be pushed into newArr in your program is if every value in that subarray equals the element that’s being checked for. So each time the value you’re trying to filter isn’t found, it pushes the entire subarray. Log your newArr into the console to see exactly what’s going on.
You don’t want to push a subarray everytime a value in subarray doesn’t match your elem. You need to push a subarray only after you check everything in the subarray that there is no match.
For example, look at this subarray[1, 6, 4] with element being 3. You are pushing this subarray without checking if this subarray contains 3 first. You are just pushing it because the first value which is 1 doesn’t match 3.
The includes method has not been covered in the lessons yet. And I don’t see how indexof() can be used here… im confused…Could you please explain what my code is doing?
function filteredArray(arr, elem) {
let newArr = [];
// change code below this line
for (var i = 0; i < arr.length; i++) {
if (arr[i].includes(elem) === false) {
newArr.push(arr[i]);
}
}
// change code above this line
return newArr;
}
// change code here to test different cases:
console.log(filteredArray([[3, 2, 3], [1, 6, 4], [3, 13, 26], [19, 3, 9]], 3));
Like I said above, you can also use method index of which essentially does the same thing.
Or you could run the double for loops like your original code and make a boolean flag before your 2nd loop runs. Only change the flag if it meets your condition and when the inner loop exits, if the boolean variable is changed then push the subarray.