You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数组排序时将Null值置于末尾的实现问题

解决Null值排末尾但保留0值正常排序的问题

我懂你的痛点——原代码里的!!_.get(x, pAttr, null)判断逻辑把所有JS假值(包括0、空字符串、false)都和null一起丢到末尾了,但你需要0作为有效数值留在正常排序位置,只有null去最后。

问题出在!!运算符上:它会把0、''、false这些你认为有效的值也转换成false,导致它们被分到了null所在的分组里。我们只需要把分区条件改成严格判断属性值是否为null就行。

修正后的代码如下:

function orderByWithNullsAtEnd(pArray: any[], pAttr: string, pReverse: boolean) {
  // 仅筛选出属性值不为null的元素作为第一组
  const partition = _.partition(pArray, (x) => _.get(x, pAttr, null) !== null);
  // 对非null组正常排序,再拼接null组到末尾
  return _.concat(_.orderBy(partition[0], pAttr, pReverse ? 'desc' : 'asc'), partition[1]);
}

为什么这样改?

  • 原条件!!_.get(...):只要属性值是假值(包括0),都会被判定为false,进入末尾分组。
  • 新条件_.get(x, pAttr, null) !== null:只有当属性值严格等于null时,才会进入末尾分组。0、false、空字符串这些假值会留在第一组,参与正常的升序/降序排序。

测试示例

假设你有这样的测试数组:

const testData = [
  { score: 80 },
  { score: 0 },
  { score: null },
  { score: 50 },
  { score: null },
  { score: 95 }
];

调用升序排序:orderByWithNullsAtEnd(testData, 'score', false),结果会是:

[
  { score: 0 },
  { score: 50 },
  { score: 80 },
  { score: 95 },
  { score: null },
  { score: null }
]

0出现在正确的升序位置,所有null都被移到了末尾,完全符合你的需求。

如果你的场景里还需要把undefined也放到末尾,可以把条件改成_.get(x, pAttr) != null(双等号,同时匹配null和undefined),根据你的实际需求调整就行。

内容的提问来源于stack exchange,提问作者hamz123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:28:23