I have simple JS(jquery) code and I would like to run it through all three nested arrays. Now it only executes first nested array ([16, 10, 11) and then stops. I have read that "for" loop may work, but I tried and failed :[

Is any1 capable of solving this problem? I will be grateful!

$(function(){ 
    var cat = [[16, 10, 11],[15, 10, 11],[36, 10, 11]];
    $('li#hcategory_' + cat[0][0] + ' ul.level2 > li:gt(' + cat[0][1] +')').hide();
      var l = $('li#hcategory_' + cat[0][0] + ' .level2 > li').length;
      if (l > cat[0][2]) {
          $('li#hcategory_' + cat[0][0] + 'span.show_more_button').show();
      } else {
          $('li#hcategory_' + cat[0][0] + 'span.show_more_button').hide();
      }
      $('li#hcategory_16 .show_more_button').click(function () {
        $('li#hcategory_' + cat[0][0] + ' ul.level2 > li:gt(' + cat[0][1] +')').show('slow');
    });
});
share|improve this question

You could use Array#forEach() for iterating.

The forEach() method executes a provided function once per array element.

$(function () {
    var cat = [[16, 10, 11], [15, 10, 11], [36, 10, 11]];
    cat.forEach(function (c) {
        $('li#hcategory_' + c[0] + ' ul.level2 > li:gt(' + c[1] + ')').hide();
        var l = $('li#hcategory_' + c[0] + ' .level2 > li').length;
        if (l > c[2]) {
            $('li#hcategory_' + c[0] + 'span.show_more_button').show();
        } else {
            $('li#hcategory_' + c[0] + 'span.show_more_button').hide();
        }
        $('li#hcategory_16 .show_more_button').click(function () {
            $('li#hcategory_' + c[0] + ' ul.level2 > li:gt(' + c[1] + ')').show('slow');
        });
    });
});
share|improve this answer
    
Thank you so much! It works great. I just had to change line 10th into: $('li#hcategory_' + c[0] + ' .show_more_button').click(function () { It was my fault because I forgot to remove "16" from there :) – Paweł Bednarczyk May 20 '16 at 18:06

You can use a double nested forEach() method first for the main array and the second for each nested array like such:

var cat = [[16, 10, 11],[15, 10, 11],[36, 10, 11]];

 cat.forEach(function(v,i){
     //here v represents the values of the first level,
     //assuming it contains only arrays you can run a nested 
     console.log(v);
     v.forEach(function(vv, ii){
         // here you can access booth arrays respectively calling them
     console.log(v);
     conosole.log(vv);
     });
});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.