javascript - Output a result array with a grouped count of unique elements for a given array -
this question has answer here:
- array value count javascript 4 answers
if have array how can loop through , push counts a new array?
wlcomed!
var products = [ ['product a'], ['product a'], ['product a'], ['product a'], ['product a'], ['product b'], ['product b'], ['product b'], ['product b'], ['product b'], ['product b'], ['product b'], ['product b'], ['product b'], ['old product b'], ['old product b'], ['old product b'], ['old product b'], ['old product b'], ['old product] ];
end goal :
var uniqueproducts = [ ['product a',5], ['product b',6], ['old product b',9] ];
accomplished doing simple coding expected result. http://jsfiddle.net/y9a8l/
function groupby(arrparam) { var result = []; var lastitem = null; var item = null; var index = -1; (var = 0; < arrparam.length ; i++ ) { item = arrparam[i][0]; if (lastitem != item) { result.push([item,1]); index++; } else { result[index][1]++; } lastitem = item } console.log(result) } groupby(products);
Comments
Post a Comment