# Help for the double for loops

Help for the double for loops
0

#1

Tell us what’s happening:
I dont know why it keeps saying Cannot read property ‘length’ of undefined.
I tested it e.g. console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 6));
and it is safe. And I dont know which part is wrong.

``````
function filteredArray(arr, elem) {
let newArr = [];
// change code below this line
for (let i = 0; i < arr.length; i++){
for (let j = 0; j < arr[i].length; j++){
if (arr[i][j] == elem){
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]], 6));
``````

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36`.

#2

You don’t want to splice subarrays but you want to splice items in subarrays.

#3

Sometimes there is so much for-loops can do. It is good to research the variety of diferent Array methods available in javascript. Array.map & Array.filter are very important, a real Swiss knife that comes handy when dealing with data in form of Arrays:

function filteredArray(arr, ele){
return arr.map(function(innerray){
return innerray.filter(function(e){
return e !== ele;});
});

}
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 6));
// [ [ 3, 2, 3 ], [1,3], [ 3, 13, 26 ], [ 19, 3, 9 ] ]

The Array.filter method returns ONLY (meaning: makes an array with elements that match a given condition, in this case, if any of element is not equal 6), it does it automatically and you don’t have to worry about positions neither to provide an empty array to be filled…etc…etc. Hope it helps

#4

Thanks for help of everyone.

I write the alternative one:
for (let i = 0; i < arr.length; i++){
if(arr[i].indexOf(elem) < 0 ){
newArr.push(arr[i]);
}
}

It is simpler and it works finally. I use the trick of previous exercise.