[英]How to move all zero values to the end of the array with LoDash/Underscore?
假設我有一個對象數組:
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 ;
});
您可以使用下划線庫來執行此操作
var _ = require("underscore");
var result = _.partition(a, function(currentObject) {
return currentObject.value !== 0;
});
console.log(_.flatten([_.sortBy(result[0], "value"), result[1]]));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.