Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over two arrays using jQuery.each()?

How can I iterate two arrays through a single call to jQuery .each()?

Something like this clearly won't work:

$.each(arr1, arr2, function(i,v){
  //do something...
});

So how can this be done?

like image 601
Sam Avatar asked Aug 05 '12 14:08

Sam


People also ask

What is the use of each () method in jQuery?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

Can we use forEach loop in jQuery?

forEach() methods. There are also libraries like foreach which let you iterate over the key value pairs of either an array-like object or a dictionary-like object. Remember: $. each() and $(selector).

What is the role of two array method in jQuery?

The jQuery merge() method together merges the content of two arrays into the first array. This method returns the merged array. The merge() method forms an array containing the elements of both arrays. If we require the first array, we should copy it before calling the merge() method.

How do I get out of each loop in jQuery?

To break a $. each or $(selector). each loop, you have to return false in the loop callback. Returning true skips to the next iteration, equivalent to a continue in a normal loop.


2 Answers

An alternative to .concat would be double $.each:

$.each([arr1, arr2], function() {
    $.each(this, function(i, v) {
        // do something
    });
});

This could turn out being faster if the arrays contain lots of items.

like image 107
Jon Avatar answered Sep 20 '22 04:09

Jon


@PPvG this is the code I though, I got two arrays that contains few words each, and using $.each() I wanted to append them in <p> tag arr1 and arr2. content of arr1 first arr2 secondo it's no matter sequence. – Sam 4 secs ago

You could .concat them for the iteration:

$.each(arr1.concat(arr2), function(i,v){
  //do something...
});

Demo: http://jsfiddle.net/ZG4wq/2/

like image 22
Esailija Avatar answered Sep 21 '22 04:09

Esailija