好吧,我有一个对象数组,其中包含某个属性的空值。
出于排序目的,该对象大致如下所示...(40 个元素,但这就足够了...)。
需要根据roulette
降序排序(roulette
有时为空),然后是新颖性
,然后是流行度
.
我的头有点痛了。
这可以按降序对轮盘
进行排序,但我需要如何扩展它以包含其他两个条件?
对象:
[
{
title: 'one',
popularity: 4,
novelty: 3
},
{
title: 'two',
popularity: 1
novelty: 4
},
{
title: 'three',
popularity: 5,
novelty: 3,
roulette: 0
},
{
title: 'four',
popularity: 5,
novelty: 3,
roulette: 1
}
]
部分工作功能:
object.sort(function(a, b) {
if (a['roulette'] == null) return 1
if (b['roulette'] == null) return -1
if (a['roulette'] === b['roulette']) return 0
return b.roulette > a.roulette ? 1 : -1
});
最佳答案
尝试按优先级和组进行排序。
var data = [{ title: 'one', popularity: 4, novelty: 3 }, { title: 'two', popularity: 1, novelty: 4 }, { title: 'three', popularity: 5, novelty: 3, roulette: 0 }, { title: 'four', popularity: 5, novelty: 3, roulette: 1 }, { title: 'five', popularity: 5, novelty: 4, roulette: null }, { title: 'six', popularity: 5, novelty: 5, roulette: undefined }];
data.sort(function (a, b) {
return (
(a.roulette === undefined || a.roulette === null) - (b.roulette === undefined || b.roulette === null) ||
a.roulette - b.roulette ||
a.novelty - b.novelty ||
a.popularity - b.popularity
);
});
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 按具有空值的多个条件对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40542564/