按两个条件对数据进行排序? [英] Sorting data by two conditions?
问题描述
我有一个JSON对象,我想按时间和用户名的字母顺序对其进行排序:
I have a JSON object and I'm trying to sort it by both time and username alphabetically:
样本数据:
const obj = [ {"timestamp": 1487184625, "user": "Eric", "action": "navigate"},
{"timestamp": 1487184655, "user": "Bill", "action": "browse"},
{"timestamp": 1487184685, "user": "Eric", "action": "key press"},
{"timestamp": 1487184715, "user": "John", "action": "idle"},
{"timestamp": 1487184755, "user": "Tran", "action": "search"},
{"timestamp": 1487098049, "user": "Tran", "action": "click"},
{"timestamp": 1487098079, "user": "Eric", "action": "click"},
{"timestamp": 1487098109, "user": "Tran", "action": "click"},
{"timestamp": 1487098139, "user": "Bill", "action": "navigate"},
{"timestamp": 1487184625, "user": "Eric", "action": "navigate"},
{"timestamp": 1487184655, "user": "Bill", "action": "browse"},
{"timestamp": 1487184685, "user": "Eric", "action": "key press"},
{"timestamp": 1487184715, "user": "John", "action": "idle"},
{"timestamp": 1487184755, "user": "Tran", "action": "search"},
{"timestamp": 1487098049, "user": "Tran", "action": "click"},
{"timestamp": 1487098079, "user": "Eric", "action": "click"},
{"timestamp": 1487098109, "user": "Tran", "action": "click"},
{"timestamp": 1487098139, "user": "Bill", "action": "navigate"}]
我尝试过这样的事情:
console.log(obj.sort((a,b) => {
// if(a.user.localeCompare(b.user)){
// return 1
// }
// if(!a.user.localeCompare(b.user)){
// return -1
// }
if(a.timestamp > b.timestamp){
return -1
}
if(a.timestamp < b.timestamp){
return 1
}
}))
但是我似乎无法正常工作.我也想避免使用Lodash.有什么建议吗?
But I can't seem to get it working. I'd like to avoid using Lodash as well. Any suggestions?
推荐答案
在属性user
上检查localeCompare
的结果,如果它是-1
或1
,则返回该结果.否则(结果为0
),返回timestamp
的比较:
Check the result of localeCompare
on the property user
, if it is either -1
or 1
then return that result. Otherwise (result is 0
), return the comparaison of timestamp
:
obj.sort((a,b) => {
var userComparaison = a.user.localeCompare(b.user);
if(userComparaison) { // userComparaison is either -1 or 1 (both are thruthy values)
return userComparaison; // return userComparaison as the sorting criteria
} else { // otherwise (userComparaison is 0 which is falsy)
return b.timestamp - a.timestamp; // compare by timestamp
}
}
使用逻辑||
可以更短:
obj.sort((a,b) => {
return a.user.localeCompare(b.user) || b.timestamp - a.timestamp;
}
如果localeCompare
返回真实值(即 -1
或1
),则将返回该真实值,而||
的其余部分将被忽略.如果返回假值(即 0
),则将返回||
的另一个操作数的值(按timestamp
排序)
if localeCompare
returned a truthy value (i.e. -1
or 1
), then that truthy value will be returned and the rest of ||
will be ignored. If it returned a falsy value (i.e. 0
) then the value of the other operand of ||
will be returned (which is sorting by timestamp
)
这篇关于按两个条件对数据进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!