简体   繁体   English

Lodash / JS orderBy与嵌套的空值

[英]Lodash/JS orderBy with nested null values

My question is kinda linked to this one, but one step more complex : lodash orderby with null and real values not ordering correctly 我的问题有点与此相关,但更复杂了一步: lodash orderby的null和实数值未正确排序

Basically I have something like this : 基本上我有这样的事情:

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

The user can pass different values for sorting, like xy or just a and sometimes x is null. 用户可以传递不同的值进行排序,例如xy或只是a ,有时x为null。 So when I use the normal _.orderBy(objs, sortKeys, ['desc']) it shows null values first. 因此,当我使用普通的_.orderBy(objs, sortKeys, ['desc'])它将首先显示空值。

How can I do so that the null values appears last? 如何使空值最后出现?

This solution partitions the array to values that are null or undefined ( unsortable ) via _.isNil() . 此解决方案通过_.isNil()将数组划分为nullundefinedunsortable _.isNil() It then sorts the sortable items, and concats the unsortable to the end: 然后,它对sortable项进行sortable ,并将不可sortableunsortable到最后:

 const { partition, get, isNil, orderBy } = _; const fn = (arr, key, order) => { const [unsortable, sortable] = partition(arr, o => isNil(get(o, key))); return orderBy(sortable, key, order) .concat(unsortable); } const objs = [{x: {y: 1, z: 2}, a: 3}, {x: {y: 4, z: 2}, a: 3}, {x: null, a: 4}]; const result = fn(objs, 'x.y', 'desc'); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script> 

Pure ES6 solution would look like this: 纯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 are simply weighted at a maximum possible value and sorted accordingly. null仅在最大可能值处加权,然后进行相应排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM