Basic Data Structures Iterate Through All an Array's Items Using For Loops

What is wrong with this code, I get an error TypeError: unknown: Cannot read property ‘0’ of undefined

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

I strongly suggest you include all brackets to help with code readability. For example, don’t do this:
if (arr[i][j]==elem) flag=false;
do:

if (arr[i][j]==elem) {
    flag=false;
}

If you go through your code and ensure your brackets are all present and accounted for, you’ll have a better result.

@Mcalex,

I did that, thanks. I dont know what was different though with putting in the brackets, cause it seems

for (let i=0;i<arr.length;i++)
 for (let j=0;j<arr[i].length;j++)
  if (.....)

didnt work, but

for (let i=0;i<arr.length;i++)
{
 for (let j=0;j<arr[i].length;j++)
{
  if (.....)
{
}
}
}

worked. I thought that even a for loop or if loop doesnt need parentheses if only one statement is supposed to follow. But oh well, it works now, thank you

This is true:

I thought that even a for loop or if loop doesn’t need parentheses if only one statement is supposed to follow

but
if if (arr[i][j]==elem) flag=false;
is two statements. And therefore the for (let j=0;j<arr[i].length;j++) line surrounding it needs braces. I use braces everywhere as it reduces these types of problem.