如何通过排序将 undefined 或 null 推到数组后面?

问题描述 投票:0回答:2

我的数组中有 3 个项目,每个项目都有一个名为

distanceFromUser
的属性,它只是一个
number
。其中两个对象的该属性具有
undefined

如果我运行

items.sort((a,b) => a.distanceFromUser - b.distanceFromUser);
,则带有
undefined
null
的两个对象将首先放入数组中。我怎样才能让它们进入阵列的后面?

javascript sorting logic
2个回答
2
投票

您可以检查

undefined
null
的值并将它们排序到数组的末尾,同时使用链式方法保留距离的顺序。

var items = [{ id: 1, distanceFromUser: undefined }, { id: 2, distanceFromUser: 1 }, { id: 3, distanceFromUser: 2 }, { id: 4, distanceFromUser: 5 }, { id: 5, distanceFromUser: 1 }, { id: 6, distanceFromUser: undefined }, { id: 7, distanceFromUser: null }, { id: 8, distanceFromUser: null }];

items.sort(
    (a, b) => 
        (a.distanceFromUser === undefined || a.distanceFromUser === null) -
        (b.distanceFromUser === undefined || b.distanceFromUser === null) ||
        a.distanceFromUser - b.distanceFromUser
);

console.log(items);
.as-console-wrapper { max-height: 100% !important; top: 0; }

使用

Number.isFinite
的稍微短一些的方法(不像
Number
 那样提前转换为 
isFinite
)。

var items = [{ id: 1, distanceFromUser: undefined }, { id: 2, distanceFromUser: 1 }, { id: 3, distanceFromUser: 2 }, { id: 4, distanceFromUser: 5 }, { id: 5, distanceFromUser: 1 }, { id: 6, distanceFromUser: undefined }, { id: 7, distanceFromUser: null }, { id: 8, distanceFromUser: null }];

items.sort(
    (a, b) => 
        !Number.isFinite(a.distanceFromUser) - !Number.isFinite(b.distanceFromUser) ||
        a.distanceFromUser - b.distanceFromUser
);

console.log(items);
.as-console-wrapper { max-height: 100% !important; top: 0; }


1
投票

只需相应地修改您的比较函数即可。见下文。请注意,我使用

== null
也会检查未定义的情况(而
===
则不会)。使用 or 运算符 (
a.distanceFromUser || ...
) 或类似运算符的其他建议解决方案也相当可观,但如果 distanceFromUser 为 0,则容易出错。

let items = [
  { distanceFromUser: 1 },
  { distanceFromUser: 23 },
  { distanceFromUser: undefined },
  { distanceFromUser: 12 },
  { distanceFromUser: 2 },
  { distanceFromUser: 9 },
  { distanceFromUser: null },
];

items.sort((a, b) => {
  if (b.distanceFromUser == null)
    return -1;
  if (a.distanceFromUser == null)
    return 1;

  return b.distanceFromUser - a.distanceFromUser;
});

console.log(items);

© www.soinside.com 2019 - 2024. All rights reserved.