下划线排序算法
Underscore sortBy algorithm
我需要你的帮助来为我的应用程序做一些算法:
我有一个这样的对象:
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
你有什么建议吗?
谢谢。
在纯 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)
Lodash 是下划线的分支,允许您按对象的多个属性排序。
使用它,解决方案可能是:
_(obj.response).map(_.partial(_.get, _, 'candidate')).sortBy(['price', 'distance']).value();
这是 fiddle 如果你想玩的话。
我需要你的帮助来为我的应用程序做一些算法:
我有一个这样的对象:
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
你有什么建议吗?
谢谢。
在纯 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)
Lodash 是下划线的分支,允许您按对象的多个属性排序。
使用它,解决方案可能是:
_(obj.response).map(_.partial(_.get, _, 'candidate')).sortBy(['price', 'distance']).value();
这是 fiddle 如果你想玩的话。