我正在尝试按升序对对象列表进行排序。但在某些情况下,排序值为 null
,在这种情况下,该值应按字母顺序排序。
我尝试创建以下代码:
let items = [
{
name: 'Foo',
Km: null
},
{
name: 'Bar',
Km: 4
},
{
name: 'BarFoo',
Km: null
},
{
name: 'FooBar',
Km: 1
},
]
function sortNullValues(values) {
values.sort(function (a, b) {
if(a.Km === null) return 1
if(b.Km === null) return -1
if (a.Km < b.Km) return 1
if (a.Km < b.Km) return -1
if (a.name > b.name) return -1
if (a.name < b.name) return 1
})
return values
}
console.log(sortNullValues(items))
但是 null
值对象没有按字母顺序排序。 https://jsfiddle.net/am7n61ou/56/
当前输出:
[
{
name: 'Bar',
Km: 4
},
{
name: 'FooBar',
Km: 1
},
{
name: 'Foo',
Km: null
},
{
name: 'BarFoo',
Km: null
}
]
期望的输出:
[
{
name: 'FooBar',
Km: 1
},
{
name: 'Bar',
Km: 4
},
{
name: 'BarFoo',
Km: null
},
{
name: 'Foo',
Km: null
}
]
最佳答案
您可以先将 null
值排序到底部,按 Km
(null - null
为零)或按字符串排序。
var array = [{ name: 'Foo', Km: null }, { name: 'Bar', Km: 4 }, { name: 'BarFoo', Km: null }, { name: 'FooBar', Km: 1 }];
array.sort((a, b) =>
(a.Km === null) - (b.Km === null) ||
a.Km - b.Km ||
a.name.localeCompare(b.name)
);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 根据对象中的另一个变量对空值进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55598843/