如何移动所有的零值与LoDash/下划线数组的结束

How to move all zero values to the end of the array with LoDash/Underscore?

本文关键字:LoDash 下划线 结束 数组 移动 何移动      更新时间:2023-09-26

假设我有一个对象数组:

    var a = [
      {label: 'one', value: 0},
      {label: 'two', value: 5},
      {label: 'three', value: 9},
      {label: 'four', value: 4},
      {label: 'five', value: 2},
      {label: 'six', value: 0}
    ]

现在我需要把所有的项按升序排列这在_.sortBy中很容易做到,但然后我想把从数组开始到末尾的所有零值,所以我的值行看起来像2, 4, 5, 9, 0, 0 ?

您可以使用自定义迭代器和Infinity属性来表示0的值,从而将它们推到末尾:

var s = _.sortBy(a, function(o) {
    return o.value || Infinity ;
});
http://jsfiddle.net/nikoshr/LwYpq/

你可以用下划线库来做,像这样

var _ = require("underscore");
var result = _.partition(a, function(currentObject) {
    return currentObject.value !== 0;
});
console.log(_.flatten([_.sortBy(result[0], "value"), result[1]]));