RulerNature RulerNature - 2 months ago 8
Javascript Question

Return an array for each column from grid

I have this function that is returning all elements of my grid but on column:

var cols = function(){
var c = $('.row');
for (var i = 0; i < c.length; i++) {
for (var j = 0; j < c.length; j++){
var x = c[j].children[i];
console.log(x);
//if(x != 0 ){return c;}
}
}
}
cols();


That means this function will take each element from my grid and will loop from top to bottom and after that will take the second column and so on.

I want to return an array for each column, I also have some classes on first row called header and other ethos will be to count between header classes n elements and return an array but I don't know how to do that :|

fiddle:

Answer

Just push all the objects from the inner for loop into an array which is created in the outer for loop:

var cols = function(){
    var c = $('.row');
    for (var i = 0; i < c.length; i++) {
      var tmp_array = [];
      for (var j = 0; j < c.length; j++){
        var x = c[j].children[i];
        tmp_array.push(x);
         //x.css({'background': 'rgba(255, 255, 255, 0.3)'});
        //if(x != 0 ){return c;}
      }
      console.log(tmp_array);
    }
}

Updated fiddle: https://jsfiddle.net/c310st3o/4/

Comments