javascript - 带有嵌套空值的 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'])
,它首先显示空值。
我怎样才能使空值最后出现?
解决方案
纯 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 只是以最大可能值加权并相应排序。
推荐阅读
- xcode - 'UIApplicationExitsOnSuspend'
- matlab - 如何在 Matlab 中测量这些黑色区域
- node.js - JSON.parse 正在从 Google Books API 创建空/未定义的对象。无法在 NodeJS 中迭代
- java - Android Studio 中的响应式视图
- postgresql - 从存储过程中获取标识
- c# - 通过 topshelf (.net core 2.2) 使用 hangfire 作为 Windows 服务
- ios - 如何在应用程序主包中设置另一个 Info.plist 而不是主 Info.plist 文件(对于一些次要属性)?
- ruby-on-rails - 如何在cmder中修复'make failedNo such file or directory'
- spring - Spring security antMatcher 未按预期工作
- recursion - 从 Groovy 或 Java 中的复杂数据结构中删除空值