Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating jquery each loop for two arrays at once

I have two Javascript arrays of same size

var demo=new Array();
var demo3=new Array();

I need to access the value of the two array in one each loop in JQuery code.After surfing for a while I came across zip operation and I tried using the code

$.zip(demo,demo3).each(function(){                                   
    alert("demo "+this[0]);
    alert("demo3 "+this[1]);      
});

However this code does not work.Please help.

like image 261
Priya Avatar asked Sep 25 '12 14:09

Priya


3 Answers

Since they're the same size, just loop one, and reference the other with i.

$.each(demo, function(i, item) {
    console.log(demo[i], demo3[i]);
});

If you don't need the indices paired, then just run them back to back by using .concat.

$.each(demo.concat(demo3), function(i, item) {
    console.log(item);
});
like image 86
I Hate Lazy Avatar answered Nov 04 '22 03:11

I Hate Lazy


Sure they'll keep same size? Use a good ol' for:

for(var i = 0; i < demo.length; i++){
    console.log(demo[i]);
    console.log(demo3[i]);
}
like image 22
moonwave99 Avatar answered Nov 04 '22 02:11

moonwave99


Try using .concat if you want to joint iterate..

$.each(demo.concat(demo3), function (idx, el) {
     alert(el);
});

else simply iterate the array and use the index to access next..

$.each(demo, function (idx, el) {
     alert(el);
     alert(demo3[idx]);
});
like image 3
Selvakumar Arumugam Avatar answered Nov 04 '22 03:11

Selvakumar Arumugam