# Outputting from nested for loops

so I have this code that works fine:

``````function filteredArray(arr, elem) {
let newArr = [];
// change code below this line

let x = false;
for(var i = 0; i<arr.length; i++){

for(var j=0; j < arr[i].length; j++){
if(arr[i][j]==elem){x = true}
}
if(x==false){newArr.push(arr[i])};
x = false;
}
// 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));
``````

but I was wondering if there was a more elegant solution to this than setting x to false/true because this by itself takes up 3 lines of code… (If I put the .push inside the nested for-loop it will push every array 3 times, The goal of the function is to only push the nested arrays that do not have “elem” inside of them) (I want to use for loops, I know I can use filter() but I’m sure this won’t be the last time I encounter this problem)

``````function filteredArray(arr, elem) {
let newArr = [];
// change code below this line
for (let i of arr) {
if (i.includes(elem)) {
continue; // to the next arr
} else {
newArr.push(i); // this arr
}
}
// change code above this line
return newArr;
}

filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)
``````
1 Like

the break method is what I was looking for though! And I didn’t know about for(let i of arr) either so thats already a great help, I’ll also play around with your code a little bit 1 Like

I have fixed the function above

1 Like