下划线sortBy算法

时间:2016-10-05 15:59:32

标签: javascript arrays underscore.js

我需要你的帮助,为我的应用程序提供一些算法:

我有一个像这样的对象:

var obj = { "response" : [
    "candidate" : {
        "id":"1",
        "price" : 10,
        "distance" : 20
    },
    "candidate" : {
        "id":"2"
        "price" : 14,
        "distance" : 2
    },
    "candidate" : {
        "id":"3",
        "price" : 200,
        "distance" : 1
    }
] }

我按这样的价格排序:

var sortPrice = _(obj.response).sortBy(function(p){
    return p.candidate.price
})

它工作正常并对对象(ids)进行排序:1,2,3

现在如果候选人的价格相同但距离不同,我应该首先显示具有相同价格和最低距离的候选人:

var obj = { "response" : [
    "candidate" : {
        "id":"1",
        "price" : 10,
        "distance" : 20
    },
    "candidate" : {
        "id":"2"
        "price" : 10,
        "distance" : 2
    },
    "candidate" : {
        "id":"3",
        "price" : 200,
        "distance" : 1
    }
] }

var sorted = _(obj.response).chain().sortBy(function (p) { 
    return parseInt(p.candidate.price) ; 
}).sortBy(function(d){
    return parseInt(d.candidate.distance)
}).value();

但它排序我的最低距离(ids):3(距离1),2(距离2),1(距离20)比2,1,3

你有什么建议吗?

谢谢。

2 个答案:

答案 0 :(得分:1)

在纯粹的js中,你可以像这样使用sort()

var obj = {
  "response": [{
    "candidate": {
      "id": "1",
      "price": 8,
      "distance": 20
    }
  }, {
    "candidate": {
      "id": "2",
      "price": 8,
      "distance": 2
    }
  }, {
    "candidate": {
      "id": "3",
      "price": 200,
      "distance": 1
    }
  }]
}

obj.response.sort(function(a, b) {
  return a.candidate.price - b.candidate.price || a.candidate.distance - b.candidate.distance;
})

console.log(obj.response)

答案 1 :(得分:0)

Lodash是一个下划线,允许您按对象的多个属性进行排序。

使用它,解决方案可能是:

_(obj.response).map(_.partial(_.get, _, 'candidate')).sortBy(['price', 'distance']).value();

如果你想玩它,请点击fiddle