Javascript - how do i do a array group and count it, like in MySQL group by given column id? -
i have big array bellow, need grouping first column , count total of channel existence.
for example:
var original_db = [ ["channel1", "online"], ["channel2", "offline"], ["channel3", "online"], ["channel1", "online"], ["lot more"].... ]
expected result original result need be:
var custom_db = [ ["channel1", 2], ["channel2", 0], ["channel3", 1] ]
edit:
for(var key in original_db) { var i; (i = 0; < original_db.length; += 1) { if (original_db[i][0] === original_db[key][0]) { original_db.splice(i, 1); return; } } } console.log(original_db);
use object properties first elements maintain count:
var counts = {}; (var = 0; < original.length; i++) { var key = original[i][0]; if (counts[key]) { counts[key]++; } else { counts[key] = 1; } }
you can turn final array, although i'm not sure why prefer on counts
object:
final = []; (var key in counts){ final.push([key, counts[key]]); }
javascript multidimensional-array duplicates
No comments:
Post a Comment