Skip to content Skip to sidebar Skip to footer

Javascript - Sum Of Values In Same Rows And Columns

I have JavaScript array with numbers 0 and 1 and I need to make a sum of all numbers in same row and column (if I imagine my array in two dimensions). I want to create second array

Solution 1:

var res = [];  //the 1D array to hold the sums
var hArr =  [
   [ 1, 1, 1, 1 ],
   [ 1, 1, 1, 1 ],
   [ 1, 0, 0, 1 ],
   [ 1, 1, 0, 0 ]
]; //your array


var vArr = []; //Now lets create an array of arrays with the columns of hArr

for (var j=0; j<hArr[0].length; j++) {
  var temp = [];
  for (var i=0; i<hArr.length; i++) {
      temp.push(hArr[i][j]);
  }
  vArr.push(temp);
}

//sum all the element in the line - Vertically and Horizontally
function SumVH (hInd, vInd) {
  var sum = 0;
  //add horizontal elements
  //to the left
  for(var i=(vInd-1); i>=0; i--) {
    //if a 0 is found, break
    if (hArr[hInd][i] == 0) {
      break;
    }
    sum += hArr[hInd][i];
  }

  //to the right
  for(var i=(vInd+1); i<hArr[hInd].length; i++) {
    //if a 0 is found, break
    if (hArr[hInd][i] == 0) {
      break;
    }
    sum += hArr[hInd][i];
  }

  //add vertical elements
  //towards top
  for(var i=(hInd-1); i>=0; i--) {
    //if a 0 is found, break
    if(vArr[vInd][i] == 0) {
      break;
    }
    sum += vArr[vInd][i];
  }

  //towards bottom
  for(var i=(hInd+1); i<vArr[vInd].length; i++) {
    //if a 0 is found, break
    if(vArr[vInd][i] == 0) {
      break;
    }
    sum += vArr[vInd][i];
  }  
  //console.log("hInd="+hInd+" vInd="+vInd+" Sum="+sum);
  return sum;
}

// go through the main array and get result
var sumR = 0;
//sum of each row
for (var i=0; i<hArr.length; i++) {
   for (var j=0; j<hArr[i].length; j++) {    
      sumR = SumVH(i,j);
      res.push(sumR);
   }   
}

Please check it and let me know if it is working as you expect it to work. res variable holds the result.


Post a Comment for "Javascript - Sum Of Values In Same Rows And Columns"