Loop Through an Array in JavaScript

For-each over an array in JavaScript

TL;DR

  • Your best bets are usually

    • a for-of loop (ES2015+ only; spec | MDN) - simple and async-friendly
      for (const element of theArray) {
      // ...use `element`...
      }
    • forEach (ES5+ only; spec | MDN) (or its relatives some and such) - not async-friendly (but see details)
      theArray.forEach(element => {
      // ...use `element`...
      });
    • a simple old-fashioned for loop - async-friendly
      for (let index = 0; index < theArray.length; ++index) {
      const element = theArray[index];
      // ...use `element`...
      }
    • (rarely) for-in with safeguards - async-friendly
      for (const propertyName in theArray) {
      if (/*...is an array element property (see below)...*/) {
      const element = theArray[propertyName];
      // ...use `element`...
      }
      }
  • Some quick "don't"s:

    • Don't use for-in unless you use it with safeguards or are at least aware of why it might bite you.
    • Don't use map if you're not using its return value.
      (There's sadly someone out there teaching map [spec / MDN] as though it were forEach — but as I write on my blog, that's not what it's for. If you aren't using the array it creates, don't use map.)
    • Don't use forEach if the callback does asynchronous work and you want the forEach to wait until that work is done (because it won't).

But there's lots more to explore, read on...


JavaScript has powerful semantics for looping through arrays and array-like objects. I've split the answer into two parts: Options for genuine arrays, and options for things that are just array-like, such as the arguments object, other iterable objects (ES2015+), DOM collections, and so on.

Okay, let's look at our options:

For Actual Arrays

You have five options (two supported basically forever, another added by ECMAScript 5 ["ES5"], and two more added in ECMAScript 2015 ("ES2015", aka "ES6"):

  1. Use for-of (use an iterator implicitly) (ES2015+)
  2. Use forEach and related (ES5+)
  3. Use a simple for loop
  4. Use for-in correctly
  5. Use an iterator explicitly (ES2015+)

(You can see those old specs here: ES5, ES2015, but both have been superceded; the current editor's draft is always here.)

Details:

1. Use for-of (use an iterator implicitly) (ES2015+)

ES2015 added iterators and iterables to JavaScript. Arrays are iterable (so are strings, Maps, and Sets, as well as DOM collections and lists, as you'll see later). Iterable objects provide iterators for their values. The new for-of statement loops through the values returned by an iterator:

const a = ["a", "b", "c"];
for (const element of a) { // You can use `let` instead of `const` if you like
console.log(element);
}
// a
// b
// c

Javascript: How to loop through every array's item every second

You can use an interval.
Here is an example:

var arr = [0,1,2,3,4];

var index = 0;

setInterval(function(){

console.log(arr[index++ % arr.length]);

}, 1000)

How to loop through an array containing objects and access their properties

Use forEach its a built-in array function. Array.forEach():

yourArray.forEach(function (arrayItem) {
var x = arrayItem.prop1 + 2;
console.log(x);
});

What's the fastest way to loop through an array in JavaScript?

After performing this test with most modern browsers:
https://jsben.ch/wY5fo

Currently, the fastest form of loop (and in my opinion the most syntactically obvious).

A standard for-loop with length caching

    var i = 0, len = myArray.length;
while (i < len) {
// your code
i++
}

I would say, this is definitely a case where I applaud JavaScript engine developers. A runtime should be optimized for clarity, not cleverness.

Loop through Array and return result into Array

You can use forEach function, which accepts a callback function.

forEach method executes a provided function once for each array element.

Syntax:

arr.forEach(function callback(currentValue, index, array) {

}[, thisArg]);

var shareholders = ['name1', 'name2', 'name3'];

var users=new Array();

shareholders.forEach(function(item,i){

users[i]=item;

});

console.log(users);

Why is using for...in for array iteration a bad idea?

The reason is that one construct:

var a = []; // Create a new empty array.

a[5] = 5; // Perfectly legal JavaScript that resizes the array.

for (var i = 0; i < a.length; i++) {

// Iterate over numeric indexes from 0 to 5, as everyone expects.

console.log(a[i]);

}

/* Will display:

undefined

undefined

undefined

undefined

undefined

5

*/

loop through array of objects and get all object values as a single string

You can use map and join like this

const arr = [
{ id: 1, value: "Apple" },
{ id: 1, value: "Orange" },
{ id: 1, value: "Pine Apple" },
{ id: 1, value: "Banana" },
];
const result = arr.map(({ value }) => value).join(', ')
console.log(result)

Loop through an array by set of 4 elements at a time in Javascript?

Use a for loop where i increases by 4.

Note: I was working on my answer when Jaromanda X commented the same thing.

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

for (var i = 0; i < arr.length; i += 4) {

console.log("Working with: " + arr.slice(i, i + 4));

}


Related Topics



Leave a reply



Submit