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?
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.
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).
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.
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.
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.
@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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With