There is a matrix of numbers (an array in which the number of columns and rows is the same). It is necessary to count the number of columns without 0 elements. I count only the number of zeros.

 var Matrix = [ [1, -2, 3, 4], [0, 4, 0, 8], [7, 0, -7, -45], [76, 65, -50, 3] ]; M(Matrix); function M(){ var count = 0; var countCol = Matrix.length; //общее количество столбцов for (var row = 0; row < Matrix.length; row++){ for (var col = 0; col < Matrix[row].length; col++){ if (Matrix[row][col] === 0){ count ++; } } } console.log(count); var countWithoutZero = countCol - count; console.log(countWithoutZero); } 
  • Are internal arrays rows or columns? - Grundy
  • I think the columns. - Egor
  • @ Yegor, Do you think?) - Dmitriy Simushev
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

2 answers 2

For the case when the columns are stored, you can use the functions reduce and every , or instead of every - indexOf

 var Matrix = [ [1, -2, 3, 4], [0, 4, 0, 8], [7, 0, -7, -45], [76, 65, -50, 3] ]; document.body.innerHTML = Matrix.reduce(function(count, cur){ return cur.every(function(el){ return el != 0; })? count+1 : count; },0); document.body.innerHTML = Matrix.reduce(function(count, cur){ return count + (~cur.indexOf(0) && 1); },0); 

For the case when strings are stored

 var Matrix = [ [1, -2, 3, 4], [0, 4, 0, 8], [7, 0, -7, -45], [76, 65, -50, 3] ]; function m(M){ var rowCount = M.length; if(rowCount == 0) return 0; var colCount = M[0].length; var count = 0; for(var i=0; i<colCount; i++){ for(var j=0;j<rowCount; j++){ if(M[j][i] == 0) break; } if(j == rowCount) count += 1; } return count; } document.body.innerHTML = m(Matrix); 

    For example, you can:

     function columnsWithoutZero(m) { var cnt = 0; for (var i = 0; i < m[0].length; i++) { if ( (m.filter(function (v) {return v[i] === 0;})).length ) continue; cnt++; } document.body.textContent = ('Number of columns: ' + cnt); } var matrix = [ [1, -2, 3, 4], [0, 4, 0, 8], [7, 0, -7, -45], [76, 65, -50, 3] ]; columnsWithoutZero(matrix); 

    • thanks, but something is wrong here. gives me 1, but there must be 2! or am I still confusing columns and rows? - Egor
    • @ Yegor Confuse you or not - you know better. I assumed that the columns are elements of nested arrays with the same indices. That is, the first column: 1,0,7,76, the second: -2,4,0,65, etc. - Deonis