Steven
Steven

Reputation: 1258

How do I sort an array in jQuery?

I am using an array to store occurrences of specific words in a text. The format of the data is word:number. I would like to sort the array by descending number of occurrences (ie. by value). Is there a neat way to do it? Or should I consider using a different data structure?

// This is how the array is filled.
var matches = ["word1", "word2", "word2", "word3", "word4", "word4", "word4"];  

var count = {};
$.each(matches, function(key, value) {
    if(!count[value])
        count[value] = 1;
    else
        count[value]++;
});

After the loop this is what I get and want to sort by descending values:

count = { 'word1':'1', 'word2':'2', 'word3':'1', 'word4':'3' };

What I actually want it to look like (sorted by value):

count = { 'word4':'3', 'word2':'2', 'word1':'1', 'word3':'1' };

Upvotes: 2

Views: 16250

Answers (2)

Rakesh Sankar
Rakesh Sankar

Reputation: 9415

Try this:

function sortmyway(data_A, data_B)
{
    return (data_A - data_B);
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) //[9, 18, 21, 39, 55, 108]

See the working example here.

Upvotes: 7

mahju
mahju

Reputation: 1156

I suggest you use some kind of tree for that instead as it already has the properties of a sorted map.

Upvotes: -1

Related Questions