按值

时间:2015-07-10 15:40:42

标签: javascript sorting

给定一组Objects,每个名称和分数:

[
    {score: 14, name:"apple"}
    {score: 13, name:"orange"}
    {score: 11, name:"banana"}
    {score: 11, name:"cabbage"}
    {score: 11, name:"bread"}
    {score: 2,  name:"cherry"}
    {score: 2,  name:"cheese"}
]

我如何生成这样的排名数字:

[
    {rank: 1, score: 14, name:"apple"}
    {rank: 2, score: 13, name:"orange"}
    {rank: 3, score: 11, name:"banana"}
    {rank: 3, score: 11, name:"cabbage"}
    {rank: 3, score: 11, name:"bread"}
    {rank: 6, score: 2,  name:"cherry"}
    {rank: 6, score: 2,  name:"cheese"}
]

因为它们中的一些对象绑定,所以它们得到相同的数字而后面的数字是偏移的。

1 个答案:

答案 0 :(得分:3)

带有一些逻辑的

Array.map可以解决问题:

var ranked = data.map(function(item, i) {
    if (i > 0) {
        //Get our previous list item
        var prevItem = data[i - 1];
        if (prevItem.score == item.score) {
            //Same score = same rank
            item.rank = prevItem.rank;
        } else {
            //Not the same score, give em the current iterated index + 1
            item.rank = i + 1;
        }
    } else {
        //First item takes the rank 1 spot
        item.rank = 1;
    }

    return item;
});

演示:http://jsfiddle.net/s0zvfubn/1/

var data = [
    {score: 14, name:"apple"},
    {score: 13, name:"orange"},
    {score: 11, name:"banana"},
    {score: 11, name:"cabbage"},
    {score: 11, name:"bread"},
    {score: 2,  name:"cherry"},
    {score: 2,  name:"cheese"}
]

var ranked = data.map(function(item, i) {
    if (i > 0) {
        var prevItem = data[i - 1];
        if (prevItem.score == item.score) {
            item.rank = prevItem.rank;
        } else {
            item.rank = i + 1;
        }
    } else {
        item.rank = 1;
    }
    
    return item;
});

document.write('<pre>' + JSON.stringify(ranked, null, 4) + '</pre>');