How can I loop through all the objects in an array using JavaScript?
I thought of something like this (where objects is my array of objects):
forEach(instance in objects)
But this does not seem to be correct.
How can I loop through all the objects in an array using JavaScript? I thought of something like this (where objects is my array of objects):
But this does not seem to be correct. |
||||
TL;DR
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 I'll quickly note that you can use the ES2015 options now, even on ES5 engines, by transpiling ES2015 to ES5. Search for "ES2015 transpiling" / "ES6 transpiling" for more... Okay, let's look at our options: For Actual ArraysYou have three options in ECMAScript 5 ("ES5"), the version most broadly supported at the moment, and will soon have two more in ECMAScript 2015 ("ES2015", "ES6"), the latest version of JavaScript that vendors are working on supporting:
Details: 1. Use
|
|
I would also like to add that
.forEach cannot be broken efficiently. You have to throw an exception to perform the break.
– Pijusn
May 6 '13 at 20:12
|
||
|
@Pius: If you want to break the loop, you can use
some . (I would have preferred allowing breaking forEach as well, but they, um, didn't ask me. ;-) )
– T.J. Crowder
May 6 '13 at 21:17
|
||
|
@T.J.Crowder True, even though it looks more like a work-around as it's not its primary purpose.
– Pijusn
May 6 '13 at 21:23
|
||
|
if you're using ie8 you can paste in this code to use forEach. if ( !Array.prototype.forEach ) { Array.prototype.forEach = function(fn, scope) { for(var i = 0, len = this.length; i < len; ++i) { fn.call(scope, this[i], i, this); } }; } developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– CharlesTWall3
Jun 19 '13 at 18:43
|
||
|
@CharlesTWall3: That's a seriously incorrect implementation of
forEach . Important lesson here: Just because it's on MDN, doesn't mean it's good.
– T.J. Crowder
Jun 19 '13 at 21:20
|
Edit: This answer is hopelessly out-of-date. For a more modern approach, look at the methods available on an array. Methods of interest might be:
The standard way to iterate an array in JavaScript is a vanilla
Note, however, that this approach is only good if you have a dense array, and each index is occupied by an element. If the array is sparse, then you can run into performance problems with this approach, since you will iterate over a lot of indices that do not really exist in the array. In this case, a In ECMAScript 5 there will be a forEach method on the array prototype, but it is not supported in legacy browsers. So to be able to use it consistently you must either have an environment that supports it (for example, Node.js for server side JavaScript), or use a "Polyfill". The Polyfill for this functionality is, however, trivial and since it makes the code easier to read, it is a good polyfill to include. |
|||||||||||||||||
|
If you’re using the jQuery library, you can use jQuery.each:
EDIT : As per question, user want code in javascript instead of jquery so the edit is
|
|||||||||||||||||||||
|
Some C-style languages use
There is a catch.
Additionally, ECMAScript 5 has added a
It's important to note that |
|||||||||
|
Loop backwardsI think the reverse for loop deserves a mention here:
Advantages:
Disadvantages:
Should I always use it?Some developers use the reverse for loop by default, unless there is a good reason to loop forwards. Although the performance gains are usually insignificant, it sort of screams:
However in practice that is not actually a reliable indication of intent, since it is indistinguishable from those occasions when you do care about the order, and really do need to loop in reverse. So in fact another construct would be needed to accurately express the "don't care" intent, something currently unavailable in most languages, including ECMAScript, but which could be called, for example, If order doesn't matter, and efficiency is a concern (in the innermost loop of a game or animation engine), then it may be acceptable to use the reverse for loop as your go-to pattern. Just remember that seeing a reverse for loop in existing code does not necessarily mean that the order irrelevant! It is better to use forEach()In general for higher level code where clarity and safety are greater concerns, I would recommend using
Then when you do see the reverse for loop in your code, that is a hint that it is reversed for a good reason (perhaps one of the reasons described above). And seeing a traditional forward for loop may indicate that shifting can take place. (If the discussion of intent makes no sense to you, then you and your code may benefit from watching Crockford's lecture on Programming Style & Your Brain.) How does it work?
You will notice that
TriviaSome people like to draw a little arrow in the reverse
Credits go to WYL for showing me the benefits and horrors of the reverse for loop. |
|||||||||||||
|
A forEach implementation (see in jsFiddle):
|
|||||||||
|
If you don't mind emptying the array:
|
||||
|
If you want to loop over an array, use the standard three-part
You can get some performance optimisations by caching |
|||||||||||||||||||||
|
I know this is an old post, and there are so many great answers already. For a little more completeness I figured I'd throw in another one using AngularJS. Of course, this only applies if you're using Angular, obviously, nonetheless I'd like to put it anyway.
There are different ways to use the forEach loop of angular. The simplest and probably most used is
Another way that is useful for copying items from one array to another is
Though, you don't have to do that, you can simply do the following and it's equivalent to the previous example:
Now there are pros and cons of using the Pros
Consider the following 2 nested loops, which do exactly the same thing. Let's say that we have 2 arrays of objects and each object contains an array of results, each of which has a Value property that's a string (or whatever). And let's say we need to iterate over each of the results and if they're equal then perform some action:
Granted this is a very simple hypothetical example, but I've written triple embedded for loops using the second approach and it was very hard to read, and write for that matter. Cons
I'm sure there's various other pros and cons as well, and please feel free to add any that you see fit. I feel that, bottom line, if you need efficiency, stick with just the native |
|||
|
An easy solution now would be to use the underscore.js library. It's providing many useful tools, such as A CodePen example of how it works is:
See also
|
||||
|
Probably the
The method will call from
And if you want it to be a function, you can do this:
If you want to break, a little more logic:
Example:
It returns:
|
||||
|
There are three implementations of
|
|||||
|
|
||||
|
There isn't any
However, note that there may be reasons to use an even simpler
|
||||
|
Internet Explorer 8 and below don't support forEach. Here's a polyfill for non supporting browsers;
It is taken from Mozilla's documentation. |
|||||||||||||
|
This is an iterator for NON-sparse list where the index starts at 0, which is the typical scenario when dealing with document.getElementsByTagName or document.querySelectorAll)
Examples of usage: Example #1
arr is now = [1, 4, 9] Example #2
Each p tag gets class="blue" Example #3
Every other p tag gets class="red"> Example #4
And finally, the first 20 blue p tags are changed to green Caution when using string as function: the function is created out-of-context and ought to be used only where you are certain of variable scoping. Otherwise, better to pass functions where scoping is more intuitive. |
||||
|
jQuery way using
|
|||
|
I think that the best and standard way is to use the
|
|||||
|
ECMAScript 6 will maybe contain the "for...of" construct. See for...of (MDN) for more information. You can already try it out with recent Firefox versions. |
||||
|
There's inbuilt ability to break in
This works because |
||||
|
Use:
where This produces two messages:
Example
It can be replaced with this using jQuery:
Using JavaScript
|
||||
|
I also would like to add this as a composition of a reverse loop and an answer above for someone that would like this syntax too.
Pros: The benefit for this: You have the reference already in the first like that won't need to be declared later with another line. It is handy when looping trough the object array. Cons: This will break whenever the reference is false - falsey (undefined, etc.). It can be used as an advantage though. However, it would make it a little bit harder to read. |
||||
|
As of ES6:
Where |
|||
|
If you have an array of entities received from a remote server, below is how you'd use
Here are more details about this. |
||||
|
This code list array value using
Console output is:
|
||||
|
Another thing about
Console output:
|
||||
|
My bad, here's an example, used dummy data, just see the logic:
|
|||||||||||||
|
|
|||
|
output: Mon, Tue, Wed, Thu, Fri, Sat, Sun |
||||
|
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
forEach
and not justfor
. as stated, in c# it was a bit different, and that confused me :) – Dante1986 Feb 17 '12 at 13:57