Ask Ben: Iterating Over An Array With jQuery

Posted November 17, 2008 at 8:33 AM by Ben Nadel

Tags: Javascript / DHTML, Ask Ben

Hi; I'm new to jquery. I have php array like:

$arr = array("one", "two", "three");

I would like to convert this array ( or copy its values) to jquery array and use .each. can someone show me this .

There are two different "each" methods in jQuery. One of them works on the jQuery stack (of DOM elements) and one of them is a utility object. They very might well work off of each other behind the scenes, but from an API view, these are two different methods with two different purposes. Luckily, the $.each() jQuery utility method does exactly what you need it to.

In the following demo, we are gonna take a Javascript array and, without any need to convert it to a jQuery array, loop over its values and add them to the document object model (DOM):

  • <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  • <html>
  • <head>
  • <title>Looping Over Arrays With jQuery</title>
  •  
  • <!-- Linked files. -->
  • <script type="text/javascript" src="jquery-1.2.6.min.js"></script>
  • <script type="text/javascript">
  •  
  • // Init the page once the DOM has loaded.
  • $( InitPage );
  •  
  •  
  • // Init the page.
  • function InitPage(){
  • // Get a refernce to the OL list element.
  • var jList = $( "#list" );
  •  
  • // Create our test array.
  • var arrValues = [ "one", "two", "three" ];
  •  
  • // Loop over each value in the array.
  • $.each(
  • arrValues,
  • function( intIndex, objValue ){
  •  
  • // Create a new LI HTML element out of the
  • // current value (in the iteration) and then
  • // add this value to the list.
  • jList.append(
  • $( "<li>" + objValue + "</li>" )
  • );
  • }
  • );
  •  
  • }
  •  
  • </script>
  • </head>
  • <body>
  •  
  • <h1>
  • Looping Over Arrays With jQuery
  • </h1>
  •  
  • <p>
  • Array Items:
  • </p>
  •  
  • <!---
  • This is the list into which we will be storing
  • the array items.
  • --->
  • <ol id="list">
  • <!--- List items will be added dynamically. --->
  • </ol>
  •  
  • </body>
  • </html>

Notice that the $.each() method takes two parameters - the current index of the array iteration and the value that was found in the array at that index. Once we have this value, we simply use jQuery to add it to the ordered list element on the page. Running the above code, our rendered page looks like this:

Array Items:

1. one
2. two
3. three

Now, looking at this code, it might seem that the $.each() method is actually more work than a standard FOR index-loop; and, at face value, it is. But, with this small bit of additional overhead, $.each() gives us a load of benefits. By passing each iteration value to a function, we create a new local scope in which to work, we create a Closure that has awesome potential, and we create a new variable for each loop value which removes many conflicts one can run into when binding event handlers.




Reader Comments

Nov 17, 2008 at 9:28 AM // reply »
304 Comments

Why is it that this line, $.each(, containts a pointer to your array? Ie, why isn't it: somevariable.each(


Nov 17, 2008 at 9:59 AM // reply »
10,640 Comments

@Ray,

I think that's how Prototype does it; but since jQuery doesn't alter the core javascript objects, there is no each() method in the javascript array class (at least not that I know of).


Nov 17, 2008 at 11:37 AM // reply »
304 Comments

I'm still confused though. How does the browser know that you are iterating over some variable? All you have is $. What if you had 2 arrays? Where is the 'link' - does that make sense? It would be like me doing

<cfoutput>#arrayLen()#</cfoutput>

withouth passing an array.


Nov 17, 2008 at 11:44 AM // reply »
10,640 Comments

@Ray,

I think I see what you're saying. The confusion, I think, comes from the fact that when you are dealing with the jQuery stack, you can call .each() directly on that stack:

jQueryVariable.each( fnCallback );

The $.each() utility method, on the other hand, does *not* know what variable it is acting on. That is why the $.each() method takes the target variable as its first argument:

$.each( AnyArrayVariable, fnCallback );

In either case, the "this" scope of the loop points to the current iteration value. In the former example, "this" points to the current DOM element; in the latter case, the "this" scope points to the array value (one, two, or three).

To be honest, I would not be surprised if the jQueryVariable.each() method actually turned around and called the utility method on its own internal stack.


Nov 17, 2008 at 4:14 PM // reply »
76 Comments

@Ben,

Exactly right. Also internally it $().each() does call $.each() to iterate the stack :)


Nov 17, 2008 at 5:24 PM // reply »
10,640 Comments

@Shuns,

Thanks for the clarification. I figured it would do as much just to cut down on code duplication.


Nov 17, 2008 at 9:55 PM // reply »
76 Comments

Yeah, thats sort of a key mantra with jQuery - as dry as possible


Nov 17, 2008 at 9:57 PM // reply »
10,640 Comments

@Shuns,

Word up, jQuery is rockin.


Nov 18, 2008 at 8:09 PM // reply »
47 Comments

@Ben,

Is this PHP user Ray? I want to know if he's doing PHP on the side instead of Coldfusion, lol!


Nov 19, 2008 at 8:11 AM // reply »
10,640 Comments

@Hatem,

Ha ha ha :) Php :)


Nov 24, 2009 at 1:46 AM // reply »
1 Comments

Thanks for this!


Nov 27, 2009 at 6:24 AM // reply »
1 Comments

@Ray,

I'm quite new to jQuery, but I think it's also possible to convert the array to a jQuery object and iterate it directly via each.

The jQuery intelligently handles different datatypes given as first param (selector) in init method (at least in version 1.3.2 I'm using) so these two examples should do the same thing.

// Give the array as parameter to jQuery.each
$.each(["one", "two", "three"], function(index) {
console.debug(index + ': ' + this);
});

// Give the array to $ and iterate the returned jQuery array object using its each method
$(["one", "two", "three"]).each(function(index) {
console.debug(index + ': ' + this);
});

Same amount of code though, no major difference here.


Jan 9, 2010 at 10:47 PM // reply »
10,640 Comments

@Perttu,

I am not 100% sure, but I think underneath, the $().each() method actually uses the $.each() method behind the scenes; so, to you're point, either way is good.


Jan 21, 2010 at 2:12 PM // reply »
1 Comments

Very simple implementation hash table.

//code
var Hash = function(){
var indexes = new Array();
var values = new Array();
//objHash.set('indexName', 123)
this.set = function(name,value){
var locationIndex = indexes.indexOf(name);
if(locationIndex==-1){
locationIndex = indexes.length;
indexes[locationIndex] = name;
}
values[locationIndex] = value;
}
//objHash.get('indexName')
this.get = function(name){
return values[indexes.indexOf(name)];
}

//objHash.each(function(index,value))
this.each = function(callback){
document.write(indexes.length)
for(var i=0;i<indexes.length;i++){
callback(indexes[i], values[i]);
}
}
}

//Example usage:

var names = new Hash();
names.set('steven','name@email.com');
document.write("Find " + names.get('steven') + "<br />");

names.each(function(index,value){
document.write("<li>" + index + " - "+value+"</li>");


Jan 21, 2010 at 8:58 PM // reply »
10,640 Comments

@Steven,

That's a cool idea - thanks for sharing.


Feb 18, 2010 at 4:48 PM // reply »
1 Comments

Thanks:) Your blog rocks I read it everyday and syndicate it with twitter @seacloud9! Your tips save me time I owe you one:)


Feb 22, 2010 at 9:11 PM // reply »
10,640 Comments

@Brendon,

Oh wow, that's awesome! Thanks. I'll check out your Twitter aggregation.


Jul 25, 2010 at 3:53 AM // reply »
1 Comments

Hello Ben,
I am trying to use the each statement to iterate through each item I have retrieved from the database or xml or json to absolutely position each on places which is defined in an array so that these items don't overlap each other , so I was thinking if you know how to do it as I cannot do it :( , I think I can do it by making a defined array with position value left and top and for each intindex a new position is given from the array. if you can help them please help me.

Thanks
Aimash


Jul 25, 2010 at 5:11 PM // reply »
10,640 Comments

@Muhammad,

Sorry, I am not really sure what you are asking me.


Aug 19, 2010 at 2:29 PM // reply »
1 Comments

.each(), iteration loop begins with value 0, how to set the initial value to 1. I want the loop to start from 1 not 0?


Aug 21, 2010 at 3:37 PM // reply »
10,640 Comments

@Santosh,

You could edit the core jQuery code; but that would only lead to trouble down the road. Everything in Javascript starts at zero. However, if you want to use a one-based system, I typically just alter the index value at the top of the loop.

.each(function(i,value){
i++; // Increments the i value.
});

Since the "i" index value is unique to each iteration of the callback, you won't have to worry about corrupting anything in future iterations.


Aug 25, 2010 at 10:30 AM // reply »
1 Comments

Obviously, I'm too stupid to understand, but the question is ... how do I convert a PHP array to a jquery array. Then you start with a javascript array!
Well, duh. How do you get the array from php to jquery, which is, in reality, javascript.
You kinda left out the most important part!


Aug 25, 2010 at 11:09 PM // reply »
10,640 Comments

@Churchie,

No one is stupid here :) We're all just having some good conversation! As far as PHP, I don't know enough about the PHP syntax to help you exactly - but, I can try to show you how to do in ColdFusion to get the work flow:

// Create a ColdFusion array.
<cfset cfArray = [ 1, 2, 3 ] />

... now, here are a *few* ways to go from a ColdFusion array to a Javascript array:

// Convert CF array to Javascript array.
var jsArray = [ #arrayToList( cfArray )# ];

// Convert CF array to Javascript array using JSON.
var jsArray = #serializeJSON( cfArray )#;

// Convert CF array to Javascript array manually.
var jsArray = [];
<cfloop index="item" array="#cfArray#">
jsArray[ jsArray.length ] = "#item#";
</cfloop>

... I know PHP must be different, but I hope that helps a bit?


Sep 24, 2010 at 3:16 AM // reply »
2 Comments

@Churchie,

you could try echoing a string of joined PHP array in to the javascript

<?php
$phpArray = Array{"one","two","three"};

// convert it into string by using php join()
$phpString = "'".join("','",$phpArray)."'"; // 'one','two','three'

// echo it (write it to the source)

echo "var jsArr=[ $phpString ];";

?>

and when the page loaded you will have a javascript array

var jsArr=[ 'one','two','three' ];

Hope it helps


Sep 24, 2010 at 3:19 AM // reply »
2 Comments

oops..
sorry..
the PHP array should be in parentheses () not curly brackets {}

sorry for the double post


Feb 2, 2011 at 5:53 PM // reply »
1 Comments

Really nice site ben, hat off to ya.

@churchie
php to jquery array:

I ususally use $.ajax then pull in the data from a php file on my server, php5 has a function to convert a recordset into a json object which you can just echo out, then in the success function of the ajax call you have the data as a json object.

hope thats of some use to you.


sam
May 6, 2011 at 1:05 PM // reply »
1 Comments

Hi,
Thank you very much for script


May 6, 2011 at 2:49 PM // reply »
254 Comments

@All:

jQuery also has jQuery.map(), as opposed to the chained .map(). The chained .map() transforms one jQuery collection into a different one. But jQuery.map() does iteration, without the overhead of having to build a jQuery collection.

jQuery.map() has been able to iterate over a non-jQuery array since version 1.0. As of 1.6 (released just this week!), however, it can now iterate over the properties of an object.

http://api.jquery.com/jQuery.map/


May 6, 2011 at 4:32 PM // reply »
254 Comments

See also

http://www.learningjquery.com/2011/05/jquery-map-in-16


Aug 22, 2011 at 5:35 AM // reply »
1 Comments

Thanks for this tut... I needed and got it done...

Thumbs up


Dec 22, 2011 at 5:16 AM // reply »
2 Comments

Hey Ben,

thanks for clarifying the difference. Great post.

Matt


Dec 23, 2011 at 3:25 PM // reply »
3 Comments

Hi Ben.

hey, this post gave me some ideas on a problem i had to solve. i needed to convert a large multi-dimensional array with object elements into a nested unordered list. just wanted to let you know that your content helps out, once again!

chris


Jan 12, 2012 at 4:43 PM // reply »
1 Comments

Hi,

How to use php array in jquery and then jquery array back to php array.
Pls advise.

Thanks

Gil



Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Feb 10, 2012 at 7:21 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
Update! Instead of $(eval(options.insertAfter)).after(data['insertData']); I now use: var ajaxNode = document.createElement('span'); var parent = $(eval(options.insertAfter))[0].parentNode; ... read »
Feb 10, 2012 at 6:18 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
encountered this same, what I consider, jQuery bug last week. I'm building a site in which I load some content via AJAX. This content contains Linkedin share button placeholders which Linkedin API ne ... read »
Feb 10, 2012 at 11:30 AM
Cross-Origin Resource Sharing (CORS) AJAX Requests Between jQuery And Node.js
After you understand the concepts here, this is an awesome cheatsheet for enabling CORS in just about anything http://enable-cors.org/ ... read »
JM
Feb 10, 2012 at 9:10 AM
My Safari Browser SQLite Database Hello World Example
@Amy, Here is a very good tutorial on how to use JOIN: http://www.sqltutorial.org/sqljoin-innerjoin.aspx ... read »
Feb 10, 2012 at 4:42 AM
Building A Twitter-Inspired RESTful API Architecture In ColdFusion
This is great, very useful Ben. I spotted a small typo in the api.cgm listing: <cfthrow type="Unauthroized" /> Cheers Stefan ... read »
Feb 9, 2012 at 10:35 PM
CFDirectory Filtering Uses Pipe Character For Multiple Filters (Thanks Steve Withington)
I was wondering if there would be a filter you could apply so that you got everything but what you included in the filter. As in show me all docs that are not a .pdf. ... read »
Feb 9, 2012 at 10:29 PM
Learning ColdFusion 9: Application-Specific Data Sources
@Ben, No offence, but if people were really wanting advanced features they would be using a platform like ASP.NET MVC. CFML is so structurally compromised as a tag-based scripting language that ... read »
Feb 9, 2012 at 10:03 PM
Subversion - Cleanup Failed To Process The Following Paths
@Leviaguirre, do you still have problems with this? ... read »