3 回答
TA贡献1863条经验 获得超2个赞
您可以返回number被比较的每个对象上的属性是否存在之间的差异,或者返回它们number属性的差异(如果两个对象都具有所述属性):
var array = [
{ number: 2 },
{},
{ number: 1 }
];
array.sort((a, b) => {
const aHas = typeof a.number !== 'undefined';
const bHas = typeof b.number !== 'undefined';
return (bHas - aHas) || (aHas === true && a.number - b.number) || 0;
});
console.log(array);
TA贡献1813条经验 获得超2个赞
您可以为具有对象扩展的数组元素提供默认值: {default, ...item}
var array = [
{ number: 2 },
{},
{ number: 1 },
{},
{ number: 0 },
];
array.sort((a, b) => (
{number: Number.MAX_VALUE, ...a}.number -
{number: Number.MAX_VALUE, ...b}.number));
console.log(array);
如果您的目标尚不支持对象扩展,请将其替换为Object.assign
.
TA贡献1812条经验 获得超5个赞
解释在评论中:
let array = [
{},
{ number: 2 },
{},
{ number: 1 }
];
array.sort((a, b) => {
// two undefined values should be treated as equal ( 0 )
if( typeof a.number === 'undefined' && typeof b.number === 'undefined' )
return 0;
// if a is undefined and b isn't a should have a lower index in the array
else if( typeof a.number === 'undefined' )
return 1;
// if b is undefined and a isn't a should have a higher index in the array
else if( typeof b.number === 'undefined' )
return -1;
// if both numbers are defined compare as normal
else
return a.number - b.number;
});
console.log( array );
添加回答
举报