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

Tell us what’s happening:
I m very new to problem-solving and I am stuck on the first one. so the question asks to check if the set of nested arrays got the value passed in an element. Following is my code which isn’t right because I don’t know yet how to access each nested element or do I need another loop inside of the loop? At the moment, as I have hardcoded [0] it doesn’t display it, which is [3,2,3]. why?

  **Your code so far**
function filteredArray(arr, elem) {
let newArr = [];
// Only change code below this line
for(let i = 0; i < arr.length;i++){
  //i = 0; 0 < 4; //this is the outer one
  if(arr[i][0] !== elem){
    //arr[i] = [3,2,3]
     //[0] should 3 in [3,2,3]?
    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));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36

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

Link to the challenge:

You are correct, it needs a loop inside a loop. In words you would say:

  1. Loop over this array
  2. Take the current item every time const innerArr = arr[i]
  3. Now loop over the innerArr almost being oblivion about the outer array. Each inner item will be const innerItem=innerArr[i]

You could try playin around with code, until you can see the “loop inside the loop” succeeding…

Following is my code now, but the inner loop is repeating 4 times and I do not know why. I only know it got something to do with the length of an array

function filteredArray(arr, elem) {
  let newArr = [];
  // Only change the code below this line
  for(let i = 0; i < arr.length;i++){
    for(let x = 0; x < arr.length; x++){
      console.log(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));

Is that how many times you want to loop?

I’d recommend to follow the “words algorithm” I wrote, because each word there has specific meaning. Once you code it you will likely see why.

I didn’t understand what u mean

It would be more helpful if you were specific about what you don’t understand.

Just to add to @kevinSmith answer,
First you need to understand how the for loop works.

for(let x = 0; x < arr.length; x++)

In the above code, for loop with start with x = 0 and runs up to x < arr.length and in each iteration x will increment by one (x++ ). So you have to think when I need to stop the loop. Is it arr.length or something else? :grinning:

Hope this helps you. Happy coding !

I’ll give you a hint (look at the function name):

function logElements(arr) {

  for(let i = 0; i < arr.length; i++){
   const innerArr = arr[i]; //get current element 
   console.log("Current Element ", innerArr)
  
     for(let x = 0; x < innerArr.length; x++){
       const myNum = innerArr[x]
       console.log("Current Element ", myNum )   
    }
  }
  return ""
}

logElements([[1,2], [3,4]])
1 Like

I like ur question and the answer is, with a complex problem I get really confused. In the said example, I was like “How do I loop the nested array and what will the length of the Array that it will need to stop” is some of example I get stuck at

I really want to become a good problem-solver

Following is the latest code and I am very much lost. I do not know what I am doing & what I m doing wrong. How we do even solve-problem?

function filteredArray(arr, elem) {
  let newArr = [];
  // Only change code below this line
  for(let i = 0; i < arr.length;i++){
    const innerArr = arr[i]
    for(let i = 0; i < innerArr.length; i++){
      if(innerArr[i] !== elem){
        const set = [];
        set.push(innerArr[i])
        return set
      }
    }
    newArr.push(set)
  }
  // Only change code above this line
  return newArr;
}

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

Well, one problem I see right off the bat is this:

        return set

When you execute a return, you leave the surrounding function - it is over - is that what you want to do here?

I really want to become a good problem-solver

Good. And that just takes time and practice.

A common approach in working on algorithms is to abstract it out. Think about it outside the language. Algorithms are not language specific. Often we write them out in pseudo-code. For example, for the example in this challenge they have an example for greaterThanTen. If I were to write that out in pseudo-code, I might right:

create new array (newArr)
loop through elements of passed array (arr)
  if element is greater than 10
    add element to newArr
return newArr

Try to come up with some pseudo code for the algorithm you are facing. If you were trying to explain it to a programmer that didn’t do JS, how would you explain it? In theory, even a non-programmer should be able to understand what is going on.

You are trying to solve this with a nested loop. That is possible, but there is a slightly easier version replacing the inner loop with a method (which really have a loop hidden inside it). I’m not saying you should solve it that way, I just giving options. Either way is fine.

1 Like

Following in my new code (thanks for hints), but right now I m struggling to understand or remove part of array which is given as arg

function filteredArray(arr, elem) {
  let newArr = [];
  let set = []
  // Only change code below this line
  for(let i = 0; i < arr.length;i++){
   //access the inner loop of innerArr
   //foreach/filer set we will check if elem is not equal to
   //passed as callback
   arr[i].filter((arr)=>{
     if(arr !== elem){
       set.push([arr])
     }
   })
  }
    return set
}

The issue is that output in indiviual number as a array but I want dataset of each without the passed in arg, (my mind was all crazy wanting to do splice and remove in each array, indexOf but that is my mind going nuts).

How can i decode the issue with help of pseduo code?

You aren’t supposed to remove “part” of the array.

… return a filtered version of the passed array such that any array nested within arr containing elem has been removed.

Don’t remove part of the sub array, remove the whole sub array.

Part of the issue here is misusing filter. The purpose of filter is to return an array where the new array is a subset of the old array where each element meets a certain condition. But you are not creating a new array - you don’t have:

let newThing = arr[i].filter(...

You would have to save that value. You are using it here to iterate (loop) through the elements and do something on each element. That would be what a forEach method would do. That is not what you want to do here.

You could use a filter to solve this problem, but it would be for the outerloop. It won’t work for the inner loop because you are not trying to get subsets of the subarrays.

So, rather than filter through the subarrays, you want to check to see if they contain elem. Is there a method that sees if an element exists in an array? If you haven’t already, go to google and enter “MDN array methods”. MDN is one of the most useful sites for reference. I’m on there almost every day.

You need to find out if each subarray contains elem and then decide what to do with it. What I’m saying is that I was able to fix your solution by fixing this:

   arr[i].filter((arr)=>{
     if(arr !== elem){
       set.push([arr])
     }
   })

The logic here should be to check if elem exists in arr[i], if it does do something with it.


A not on variables…

You didn’t need to create the variable set - you already have a variable newArr. I also think that “set” isn’t a good name for an array - there is a data structure called “set” that is different than an array. Also, you have a variable called “arr” in your callback function in your filter method. You already have a variable called that in the parent scope. That is a bad idea - it can lead to mistakes.

I did it! wow I can’t believe I did it!

I was reading the question wrong, I was creating

Following is my code now

function filteredArray(arr, elem) {
  let newArr = [];
  // Only change code below this line
   //loop through the array using for
   for(let i = 0; i < arr.length - 1; i++){
     //i = 0; length 4 ; [3, 2, 3]
     //i = 1; length 4 ; [1, 6, 3]
     //i = 2; length 4 ; [3, 13, 26]
     //i = 3; length 4 ; [19, 3, 9]
     //i = 4; length 4; ?
     
    //check for nested array, if the nested array contain,
    //do not add it newArr
     const nestedArray = arr[i];
     if(!nestedArray.includes(elem)){
       newArr.push(nestedArray)
     }
   }
  // Only change code above this line
  return newArr;
}

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

Few things I am confused about, see I did comment on each i but I am confused because why there is an empty array if u do let i = 0; i < arr.length where I wrote i = 4; length 4; ? because we are saying

i is less than the length of the array so the length is 3, but still I had to do length-1.

I think I am still confused if my problem makes sense.

For:

const friends = ['Alice', 'Bob', 'Carol', 'David']

The length is 4. But you start counting with 0 so the last one will be 3:

const friends = ['Alice', 'Bob', 'Carol', 'David']

console.log('length =', friends.length)
// length = 4

for (let i = 0; i < friends.length; i++) {
  console.log(i, friends[i])
}
// 0 Alice
// 1 Bob
// 2 Carol
// 3 David

It’s called “zero indexing”. It is very common in computer programming, for historical/technical reasons.

You can’t access friends[4] because that would be the 5th element, which doesn’t exist.

1 Like

Amazing, thank you. I hope I get better at it.

You will. It’s a confusing topic for learners.

It’s like, as an American, the ground floor of a building is the “first” floor - that is one-indexing. In Europe, the first floor is the first one above the street. The bottom floor is “ground” or “street” or “0”. That is an example of zero-indexing.

It’s confusing at first, but it makes sense over time.

1 Like