Your thinking is perfectly valid but it helps even more if you know some of the built-in functions to make it considerably shorter. At first, it was tempting for me too to use your approach, but after some thinking, see below for the much shorter and compact solution:
for (let i=0; i<arr.length; i++)
{
if (arr[i].indexOf(elem)< 0)
{
newArr.push(arr[i]);
}
}
Anyone know why the following code works in the google developer console, but shows ‘i is not defined’ errors in code camp?
for(i = 0; i < arr.length ; i ++){
if (arr[i].indexOf(elem) === -1){
newArr.push(arr[i]);
};
};
Thanks!!
Solved: If anyone was wondering - i didn’t initiate the variable ‘i’ properly. I put ‘let’ at the front and it worked.
Hi, i added some comments here to give you an idea how this is working
function filteredArray(arr, elem) {
let newArr = [];
// first the for loop for length definition
for (let i = 0; i < arr.length; i++) {
// now the if clause to check if there is something ther if there is nothing you should add the array, this is the reason why we use -1 here
if (arr[i].indexOf(elem) === -1) {
// push it to the array
newArr.push(arr[i]);
};
};
// return the newArr to make it available outside the function
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));
All the best and looking forward to hear from you soon
cheers Mchoeti