首页 > 解决方案 > 带有嵌套空值的 Lodash/JS orderBy

问题描述

我的问题有点与这个有关,但更复杂一点:lodash orderby with null and real values not ordering correct

基本上我有这样的东西:

let objs = [{x: {y: 1, z: 2}, a: 3}, {x: null, a: 4}];
let sortKeys = ['x.y', 'a']; //this is dynamic, can have multiple fields

用户可以传递不同的值进行排序,例如x.y或只是a有时x为空。因此,当我使用法线时_.orderBy(objs, sortKeys, ['desc']),它首先显示空值。

我怎样才能使空值最后出现?

标签: javascriptsortinglodash

解决方案


纯 ES6 解决方案如下所示:

let objs = [{x: {y: 1, z: 2}, a: 3}, {x: null, a: 4}];

objs.sort(({x: x1}, {x: x2}) => {
  const y1 = x1 === null ? Infinity : x1.y;
  const y2 = x2 === null ? Infinity : x2.y;
  
  return y1 - y2;
});

console.log(objs);

null's 只是以最大可能值加权并相应排序。


推荐阅读