0

Possible Duplicate:
Sorting JavaScript Object by property value
Sort JavaScript object by key

I've written a function called frequency() that takes an Array, counts the number of times a string is found within it, and then returns an object based on these results.

Code:

var array = ["Diesel","Asos","Diesel","Paul Smith"];

function frequency(array) {
    var frequency = {}, value;
    for(var i = 0; i < array.length; i++) {
        value = array[i];
        if(value in frequency)
            frequency[value]++;
        else
            frequency[value] = 1;
    }
    return frequency;
}

ordered = frequency(array);

Sample output:

{"Asos":1,"Diesel":2,"Paul Smith":1}

How can I now sort this outputted object based on the counted frequency value?

Community
  • 1
  • 1
Ryan Brodie
  • 6,090
  • 7
  • 37
  • 57
  • It doesn't make sense to sort an object literal -- key/value access follows simple Map semantics. – hvgotcodes Aug 15 '12 at 15:25
  • JavaScript objects an unordered, so it is meaningless to talk about sorting them. – Matt Ball Aug 15 '12 at 15:25
  • I need to order by size of frequency in Array so I can make a top 10 most frequent? I understand that but surely something like QSORT could go through each value and reorder it? – Ryan Brodie Aug 15 '12 at 15:31
  • You're missing the point. You cannot sort something which does not have an ordering. – Matt Ball Aug 15 '12 at 15:32
  • You can do it using an array. Each array's element is an object which has frequency property, and another which contains the elements which appear at that frequency. See it here: http://jsfiddle.net/uxhCt/ – Oriol Aug 15 '12 at 16:18

0 Answers0