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. |
||||
For Actual Arrays(See "For Array-Like Objects" below for array-like objects.) You currently have three options and will soon have two more: You have three options in ECMAScript 5 (ES5), the current version of JavaScript; and will soon have two more in ECMAScript 6 (ES6), the next version of JavaScript:
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.
– Pius
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
|
||
|
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
|
||
|
|||
|
@FMC: Where I'm using it above, it doesn't make any difference whether it's
++index or index++ ; we're not using the result of that expression. The first value index will have in the loop is 0 either way. I used ++index because I speak English, and so "increment index " makes more sense to me than "index increment". But whichever you prefer is fine there.
– T.J. Crowder
Feb 3 '14 at 10:43
|
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
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 |
|||||||||||||||||||||
|
There are three implementations of
|
|||||||||
|
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:
|
||||
|
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 |
|||
|
|
||||
|
There isn't any
However, note that there may be reasons to use an even simpler
|
||||
|
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. |
||||
|
Internet Explorer 8 and below don't support forEach. Here's a polyfill for non supporting browsers;
It is taken from Mozilla's documentation. |
|||||||||||||
|
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. |
||||
|
jQuery way using
|
|||
|
Use:
where This produces two messages:
Example
It can be replaced with this using jQuery:
Using JavaScript
|
||||
|
There's no built-in ability to break in forEach. To interrupt execution use of Array#some:
This works because some returns true as soon as any of the callbacks, executed in array order, return true, short-circuiting the execution of the rest. Original Answer see Arrary prototype for some |
|||
|
One more thing about array.forEach. You can get not only index, but also the iterated object with forEach, if you have array of objects:
|
|||
|
This code list array value using forEach loop.
|
|||
|
I also would like to add this as a composition of 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 wont need to declared later with another line. Handy when looping trough the object array. Cons: This will break whenever reference is false - falsey (undefined etc). Can be used as an advantage though , however it would make it to read a little bit harder |
|||
|
Thank you for your interest in this question.
Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.
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