javascript - Create a new array adding duplicate values together -
i have 2 dimensional array:
[[bourbon, 2], [bourbon, 1],[scotch, 2]]
i end new array consolidates duplicates array become
[[bourbon, 3], [scotch, 2]]
here how create array:
for(var i=0; i< data.length; i++){ var typew = string(data[i].doc.type); var valueasnumber = parseint(data[i].doc.bottle); typeofwhiskey[j,i] = [typew,valueasnumber]; j++; }
i have tried check unique values with:if(typeofwhiskey.indexof(typew ) > -1){
however stuck. in example 'typew' string value 'bourbon', or 'scotch' example, 'valueasnumber' 2 or 1 based on example provided. not have create , iterate through whole array again because feel inefficient. think close not sure how proceed. thanks
this work:
var source = [['bourbon', 2], ['bourbon', 1],['scotch', 2]]; var hash = {}; var consolidated = []; source.foreach(function(item) { hash[item[0]] = (hash[item[0]] || 0) + item[1]; }); object.keys(hash).foreach(function(key) { consolidated.push([key, hash[key]]); });
Comments
Post a Comment