所以我有一个对象数组,我有2个布尔值,我需要按照corporate_sponsor和title的优先级排序,然后是visitor_bureau和title,然后按标题排序。
let array = [{
"title": "A Some Place",
"visitor_bureau": "0",
"corporate_sponsor" : "0"
}, {
"title": "B Some Place",
"visitor_bureau": "1",
"corporate_sponsor": "1"
}, {
"title": "C Some Place",
"visitor_bureau": "1",
"corporate_sponsor" : "1"
}];
我现在使用的代码只设置为对visitor_bureau和title进行排序,但我需要添加另一个元素。
var sorted = array.sort((a, b) => b.visitor_bureau - a.visitor_bureau || a.title.localeCompare(b.title));
非常感谢任何帮助。
答案 0 :(得分:1)
如果您可以想象将来必须添加更多属性,那么创建抽象以根据您需要的任何属性排序比每次增加您的方法(使其更复杂和更不可读)更有意义。
我已经定义了一个函数sorterBy
,您可以按优先级顺序传递一系列数组,这些数组表示您要排序的每个属性。它返回一个可以用作Array#sort
参数的函数。使用它看起来像这样(其中"排序顺序"升级为1
,降序-1
):
let sorted = [...array].sort(sorterBy(
//[<name>, <type>, <sort order>]
['corporate_sponsor', 'number', -1],
['visitor_bureau', 'number', -1],
['title', 'string', 1]
))
function sorterBy (...properties) {
return (a, b) => {
let result = 0
for (let property of properties) {
if (result) return result
else result = compare(a, b, property)
}
return result
}
}
function compare(a, b, property) {
let [name, type, direction = 1] = property
a = a[name]
b = b[name]
if (direction === -1) [b, a] = [a, b]
switch (type) {
case 'number':
a = +a
b = +b
return a < b ? -1 : a === b ? 0 : 1;
case 'string':
a += ''
b += ''
return a.localeCompare(b)
}
return 0
}
let array = [{
"title": "A Some Place",
"visitor_bureau": "0",
"corporate_sponsor" : "0"
}, {
"title": "B Some Place",
"visitor_bureau": "1",
"corporate_sponsor": "1"
}, {
"title": "C Some Place",
"visitor_bureau": "1",
"corporate_sponsor" : "1"
}]
let sorted = [...array].sort(sorterBy(
['corporate_sponsor', 'number', -1],
['visitor_bureau', 'number', -1],
['title', 'string', 1]
))
console.log(array)
console.log(sorted)
&#13;
答案 1 :(得分:0)
我最终自己搞清楚了。
var sorted = posts.sort((a, b) => b.corporate_sponsor - a.corporate_sponsor || b.visitor_bureau - a.visitor_bureau || a.title.localeCompare(b.title));