Tell us what’s happening:
Not too sure what the purpose of “== -1” does?
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){
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, 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/70.0.3538.110 Safari/537.36.
Array.prototype.indexOf() returns -1 if the element isn’t in the array. So newArr.push(arr[i]) only get’s executed if the array at arr[i] doesn’t contain elem.
This has the result of adding all arrays that don’t contain elem to newArr which results in returning an array of all arrays that don’t contain elem.
Another way to check if an array contains and element is the Array.prototype.includes() method that returns true if the array contains the element and false if it doesn’t. This method was added in ES2016 so a lot of people still use indexOf() because that’s how people checked if an array contained an element before ES2016. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes