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

I wanted to know how arr[i] accessing the values of nested array.For example if we have arr[0] and this means we are pointing to [3,2,3] and then if wanted to compare its values with elem how can we do that.The logic arr[i]==elem won’t work here because arr is a nested array.When i couldn’t solve this ,then checked the hint and found the following solution for this question and here also not getting why this if(arr[i].indexOf(elem) == -1).Please help!!!

function filteredArray(arr, elem) {
let newArr = [];
// Only change code below this line
for(let i=0;i<arr.length;i++){

if(arr[i].indexOf(elem) == -1){
newArr.push(arr[i]);
}
}
// Only change code above this line
return newArr;
}

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

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

Challenge: Basic Data Structures - Iterate Through All an Array’s Items Using For Loops

If arr[0] would be [3, 2, 3], then individual element could be accessed ie. with arr[0][0]. In this case that would be 3.

indexOf method returns -1 if element is not found in the array.

How with only one loop we are accessing values of array from array. For me a[0] is [3,2,3] and how with one loop only we are accessing 3,2, and 3 and returning -1 if match is not there.

Also, I tried solving same question this way ,I am getting correct results but returned array is not nested array anymore. How we can fix this?

function filteredArray(arr, elem) {
let newArr = [];
// Only change code below this line
let  r=arr.length;
for(let i=0;i<r;i++)
{
let n=arr[i].length;
for(let j=0;j<n;j++)
{

if (arr[i][j]!==elem)
{
newArr.push(arr[i][j]);
}
}
// Only change code above this line
}
return newArr;
}

console.log(filteredArray([[ 3, 18, 6],[2,13,16]],18));

Results are: [ 3, 6, 2, 13, 16 ];

indexOf methods checks all elements in array. Loop is iterating over array with arrays, then indexOf looks in array, from which method is called.

It’s ie. arr[0].indexOf(elem), not arr.indexOf(elem).

I wasn’t getting how indexof() is getting values from array. But now its clear. Thanks for helping me out.

Yes,You are right.I read it wrong ,we have to return sub-array that doesn’t include elem.I can’t solve this challenge the way I was doing before ,However we can use other functions such as includes() and many more instead of indexof() to getting into the sub-arrays and that also solving this challenge.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.