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?
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?
Share Improve this question edited Aug 5, 2012 at 14:31 Peter-Paul van Gemerden 7,01132 silver badges37 bronze badges asked Aug 5, 2012 at 14:16 SamSam 1,1453 gold badges14 silver badges24 bronze badges 8 | Show 3 more comments2 Answers
Reset to default 11An 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/
arr1
first, and then the values ofarr2
? Or do you want to iterate through both in parallel to process the first element from both arrays at once, then the second element from both, etc.? – nnnnnn Commented Aug 5, 2012 at 14:27