underscore.js - Using Underscore Count and Total Array Elements -
let's have these 2 javascript arrays:
var types = ["w", "x", "y", "z"]; var data = [["x", 3], ["y", 4], ["x", 2], ["z", 6], ["z", 3], ["x", 1], ["z", 2]];
using underscore.js want produce these 2 results:
var counts = [["w", 0], ["x", 3], ["y", 1], ["z", 3]]; var totals = [["w", 0], ["x", 6], ["y", 4], ["z", 11]];
the counts array counts number of instances each element appears in data array. totals array sums elements appear in data array type. need code work when there elements in types array don't appear in data array - in case there no "w" elements in data.
thanks in advance.
i looping (underscore way)
var types = ["w", "x", "y", "z"]; var data = [["x", 3], ["y", 4], ["x", 2], ["z", 6], ["z", 3], ["x", 1], ["z", 2]]; var counts = []; var totals = []; _.each(types, function(type, index){ var count = 0; var total = 0; _.each(data, function(value, index){ if(type == value[0]){ count ++; total += value[1]; } }); counts.push([type, count]); totals.push([type, total]); }); console.log(counts); console.log(totals);
Comments
Post a Comment