Yubin Qiu Yubin Qiu - 7 months ago 24
Javascript Question

Group and sum an array

I'm trying to dynamically retrieve, calculate and store some information in arrays.

Information that I have is:

var myArrayID = [];
myArrayID = ['1', '2', '3', '4', '5', '1', '2', '3', '4', '5', '1', ........ '5'];
//100 ID in myArrayID that has been sorted in order

var myArrayScore = [];
myArrayScore = ['100', '70', '80', '88', '23', '99', ....... '20'];
//100 Score in myArrayScore that has been sorted in order


In short

myArrayID[0]
has reference to
myArrayScore[0]
----> ID 1 has a score of 100

....

myArrayID[99]
has a reference to
myArrayScore[99]
----> ID 5 has a score of 20




I would like to get the total score of each individual ID without using my hardcode method

My method is

var ID1 = 1;
var ID2 = 2;
var ID3 = 3;
var ID4 = 4;
var ID5 = 5;

var ID1Score = 0;
var ID2Score = 0;
var ID3Score = 0;
var ID4Score = 0;
var ID5Score = 0;

for(var i in myArrayID)
{
if(myArrayID[i] === ID1)
{
ID1Score += myArrayScore[i];
}
if(myArrayID[i] === ID2)
{
ID1Score += myArrayScore[i];
}
if(myArrayID[i] === ID3)
{
ID1Score += myArrayScore[i];
}
if(myArrayID[i] === ID4)
{
ID1Score += myArrayScore[i];
}
if(myArrayID[i] === ID5)
{
ID1Score += myArrayScore[i];
}
}


This method works but it is hard coded.

May I know if there's anyway to code it dynamically,

In a sense that, even if my array changes (assuming i have 9 ID instead) but it is still in a sorted order and it will still contain the same LENGTH.

Answer

var myArrayID = ['1', '2', '3', '4', '5', '1', '2', '3', '4', '5']; 
var myArrayScore = ['100', '70', '80', '88', '23', '100', '70', '80', '88', '23'];


var _f = {};

myArrayID.forEach(function(el, i){
  
  if(_f.hasOwnProperty(el)){
    _f[el] += +myArrayScore[i];
  }
  
  else{
   _f[el] = +myArrayScore[i]; 
  }
  
});

alert(JSON.stringify(_f));

// Score for first:
alert("1st Score: "+_f["1"]);

// Score for second:
alert("2nd Score: "+_f["2"]);

Comments