5800

How can I loop through all the entries in an array using JavaScript?

3
  • Use for...of loop. See w3schools.com/JS/js_loop_forof.asp Commented Aug 25, 2022 at 15:28
  • Near duplicate of (but slightly more general than) "Loop through an array in JavaScript". Commented Oct 17, 2022 at 2:15
  • This question is similar to: Loop through an array in JavaScript. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Mar 24 at 13:55

41 Answers 41

1
2
7

If you want to loop through an array of objects with the arrow function:

let arr = [{name:'john', age:50}, {name:'clark', age:19}, {name:'mohan', age:26}]; arr.forEach((person)=>{ console.log('I am ' + person.name + ' and I am ' + person.age + ' old'); })

Sign up to request clarification or add additional context in comments.

Comments

5

If you have a massive array you should use iterators to gain some efficiency. Iterators are a property of certain JavaScript collections (like Map, Set, String, Array). Even, for..of uses iterator under-the-hood.

Iterators improve efficiency by letting you consume the items in a list one at a time as if they were a stream. What makes an iterator special is how it traverses a collection. Other loops need to load the entire collection up front in order to iterate over it, whereas an iterator only needs to know the current position in the collection.

You access the current item by calling the iterator’s next method. The next method will return the value of the current item and a boolean to indicate when you have reached the end of the collection. The following is an example of creating an iterator from an array.

Transform your regular array to iterator using values() method like this:

 const myArr = [2,3,4] let it = myArr.values(); console.log(it.next()); console.log(it.next()); console.log(it.next()); console.log(it.next());

You can also transform your regular array to iterator using Symbol.iterator like this:

const myArr = [2,3,4] let it = myArr[Symbol.iterator](); console.log(it.next()); console.log(it.next()); console.log(it.next()); console.log(it.next());

You can also transform your regular array to an iterator like this:

let myArr = [8, 10, 12]; function makeIterator(array) { var nextIndex = 0; return { next: function() { return nextIndex < array.length ? {value: array[nextIndex++], done: false} : {done: true}; } }; }; var it = makeIterator(myArr); console.log(it.next().value); // {value: 8, done: false} console.log(it.next().value); // {value: 10, done: false} console.log(it.next().value); // {value: 12, done: false} console.log(it.next().value); // {value: undefined, done: true}

NOTE:

  • Iterators are exhaustible in nature.
  • Objects are not iterable by default. Use for..in in that case because instead of values it works with keys.

You can read more about iteration protocol here.

Comments

5

You can use:

  1. ForEach

    theArray.forEach(function (array, index) { console.log(index); console.log(array); }); 
  2. for

    for(var i=0; i<theArray.length; i++) { console.log(i) } 
  3. map

    theArray.map(x => console.log(x)); 
  4. map

    theArray.filter(x => console.log(x)); 

And there are many others for iteration.

Comments

3

I'd argue that for/of is the way to go:

const arr = ['a', 'b', 'c']; for (const v of arr) { console.log(v); // Prints "a", "b", "c" }

  • Unlike for/in, for/of skips non-numeric properties on the array. For example, if you set arr.foo = 'test', for (var v in arr) will loop through the 'foo' key.

  • Unlike forEach(), for/of doesn't skip "holes" in arrays. const arr = ['a',, 'c'] is valid JavaScript, just the 2nd element is a "hole". The array is functionally equivalent to ['a', undefined, 'c'].

You can read more in this blog post on for/of vs forEach().

Comments

3

Suppose we have an array of subjects:

let ddl = new Array(); if (subjects) { subjects.forEach(function (s) {ddl.push({"id": s.id, "label": s.name});}); } 

1 Comment

An explanation would be in order. E.g., what is the idea/gist? From the Help Center: "...always explain why the solution you're presenting is appropriate and how it works". Please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).
2

If you want to keep your code in the functional way, use map:

theArray.map(instance => do_something); 

In this way you will generate a new array to future operation and will skip any not desirable side effect.

Comments

1

// Looping through arrays using the foreach ECMAScript 6 way var data = new Array(1, 2, 3, 4, 5); data.forEach((val,index) => { console.log("index: ", index); // Index console.log("value: ", val); // Value });

Comments

-1
var a = ["car", "bus", "truck"] a.forEach(function(item, index) { console.log("Index" + index); console.log("Element" + item); }) 

Comments

-2

I come from Python, and I found this way much clearer.

theArray being the array, and instance being the elements of the array:

for (let instance of theArray) { console.log("The instance", instance); } 

or

for (instance in theArray) { console.log("The instance", instance); } 

compare to:

theArray.forEach(function(instance) { console.log(instance); }); 

But at the end of the day both are doing the same thing.

1 Comment

for (instance in theArray) does not do the same as for (let instance of theArray). The former iterates over keys while the latter over values. So if theArray = ["a", "b", "c"] then for..in will print 0, 1, 2 while for..of will print "a", "b", "c".
-2

Mozilla documentation

/* Get all forms */ document.querySelectorAll( "form" ).forEach( form => { /* For each form, add the onsubmit event */ form.addEventListener( "submit", event => { event.preventDefault(); // Return false /* Display it */ alert(event.target.action); console.log(event.target); } ); } );
<form action="form1.php" > <input type="submit" value="Submit" /> </form> <form action="form2.php" > <input type="submit" value="Submit" /> </form> <form action="form3.php" > <input type="submit" value="Submit" /> </form>

Comments

-3

I do it like this.

foreach

const arr = ["apple", "banana", "orange", "pear", "grape"]; arr.forEach(function(element) { console.log(element); }); 

for..of

const arr = ["apple", "banana", "orange", "pear", "grape"]; for (const element of arr) { console.log(element); } 

1 Comment

There are already more than 40 nondeleted answers (77 incl. deleted). What does this add?
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.