docta_faustus - 1 year ago 183
Javascript Question

# JavaScript Array Sorting/Ranking with Equal Ranks

After sorting an array of objects based on of their property values ("rating" in this case), how do you associate ranks for each object if there are ties between some of these values? Here's an example:

``````//Should be tied for 1st Rank
var obj1 = {
name: "Person1",
rating: 99
}

//Should be 3rd Rank
var obj2 = {
name: "Person2",
rating: 50
}

//Should be 2nd Rank
var obj3 = {
name: "Person3",
rating: 98
}

//Should be 4th Rank
var obj4 = {
name: "Person4",
rating: 0
}

//Should be tied for 1st Rank
var obj5 = {
name: "Person5",
rating: 99
}
``````

Here's as far as I got:

``````var clients = [obj1, obj2, obj3, obj4, obj5];
var sorted = [];

for (var i = 0; i < clients.length; i++) {
sorted.push(clients[i]);
}

sorted.sort(function(a, b) {
return b.rating-a.rating;
});
``````

Ultimately, I'd like to be able to get the rank using the object name, like this:

``````alert(sorted.indexOf(obj5) + 1);
``````

Created a solution that worked, albeit ugly. Thanks jamie for some framework used in this:

``````for (var i = 0; i < clients.length; i++) {
sorted.push(clients[i]);
}

sorted.sort(function(a, b) {
return b.rating-a.rating;
});

for(var i = 0; i < sorted.length; i++) {
// original ranking
sorted[i].rank = i + 1;
}

function sortRanking() {
for (var k = 0; k < sorted.length; k++) {
for (var h = 1; h < sorted.length + 1; h++) {
if (sorted[k+h] !== undefined) {
if (sorted[k+h].tie !== true) {
if (sorted[k].rating === sorted[h + k].rating) {
sorted[k].rank = k + 1;
sorted[h + k].rank = k + 1;
sorted[k].tie = true;
sorted[h + k].tie = true;
}
}
}
}
}
}

sortRanking();