2

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' };
3
  • It's not a valid object, though. Either the OP meant ["word1", "word2", ... ] or he's lost his keys. Commented Jun 13, 2011 at 11:28
  • Sorry, comment was referring to the first line only (changed it). @Tomalak This is what I meant. Commented Jun 13, 2011 at 11:37
  • Please edit your post to more accurately reflect your scenario. Commented Jun 13, 2011 at 11:38

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

7 Comments

The OP doesn't have an array, but an object.
Really? I doesn't look like an object, I still see an array, see this jsfiddle.net/srakesh/82VVn/1 when I alert "list[0]" it gives me "9".
@Rakesh: What in particular do you want explaining? Objects support obj[i] syntax. Arrays are a specific form of object. Arrays are created like [1,2,3] and are numerically indexed. More general objects are created with {1:1, 2:2, 3:3} and are indexed however you like.
@Rakesh: (Actually, in fairness, it looks like the OP did in fact mean to talk about an array.)
@Rakesh: Your code has an array. I said the OP didn't have one.
|
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.