Daniel Yantis Daniel Yantis - 2 months ago 7
MySQL Question

Count duplicate values in a multidimentional Array

I don't think this is a duplicate because it deals with an object that has multiple record sets, although it is very similar, my needs require more loops i think. Either way, I can't seem to make it work for me. I'm just learning here and this is too complex for me. I need some examples using an object like this one. I've tried using some similar question-answers but always fail due to the extra level of loops needed.

My current code outputs a simple unsorted list:

for (i=0; i<data.length; i++)
if (data[i]['name'])
$("#output").append("<p>"+data[i]['entrynum']+data[i]['name']);


What I want is something like:


  • J0hn James

  • Fr3d

  • S@m Wise

  • Fr3d

  • Fr3d

  • S@m Wise

  • Fr3d

  • Fred

  • S@m Wise

  • S@m Wise

  • Frank

  • Frank

  • Bill

  • Frank

  • Bill



to output a list that reports (preferably in order desc):


  • 5 Fr3d

  • 4 S@m Wise

  • 3 Frank

  • 2 Bill

  • 1 J0hn James


Answer

I've learned much over the night! Here's what I have now:

//convert my multidimensional object into a simple list
var clublist = [];
for (i=0; i<data.length; i++)
    if (data[i]['club']) 
        clublist.push(data[i]['club']);

//counting, converted into object with occurrence & count
var counts = {};
clublist.forEach(function(x) { counts[x] = (counts[x] || 0)+1; });

//converted into an array to be sorted
var clubs = [];
for (var temp in counts)
    clubs.push([temp, counts[temp]])

//sorted array, descending
clubs.sort(function(a, b) { return b[1] - a[1] })

//final output to page
for (i=0; i<clubs.length; i++)
    $("#output").append("<p>"+clubs[i][1]+" - "+clubs[i][0]);

However, this seems like a lot of steps... any ideas on making this more compact?

Comments