How do I force Javascript to Iterate over an Object in an Array?

I’m working on one of the intermediate algorithm scripting tasks in the Data Structures course and I can’t for the life of me get Javascript to iterate over the objects in an array passed to a function. It always iterates over the array indices.

For example, if I type:

for(let obj in collection) {
  console.log(obj)
}

the output is always

0
1
2

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/114.0

Challenge: Intermediate Algorithm Scripting - Wherefore art thou

Link to the challenge:

For…in iterates over the keys:

For…of iterates over the values:

1 Like

Also, for…in might also show unwanted keys (edge case but still good to know) and ordering bugs in old IE versions. javascript - Why is using "for...in" for array iteration a bad idea? - Stack Overflow

That’s why you need a basic for loop, a for of loop, or .forEach.

1 Like

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