最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sort an array of objects in ascending order but put all zeros at the end - Stack Overflow

programmeradmin0浏览0评论

If I have an array of objects:

[{
    val: 0
}, {
    val: 1
}, {
    val: 0
}, {
    val: 3
}]

How can I sort it in ascending order, but keep the zeros at the end, like this:

[{val:1}, {val:3}, {val: 0},{val: 0}]

Sorting, as expected, puts zeros on the top. Even if I add logic to sort zeros towards the end:

array.sort((a,b) => {
    if (a.val === 0 || b.val === 0) return 1;
    return a.val < b.val;
});

If I have an array of objects:

[{
    val: 0
}, {
    val: 1
}, {
    val: 0
}, {
    val: 3
}]

How can I sort it in ascending order, but keep the zeros at the end, like this:

[{val:1}, {val:3}, {val: 0},{val: 0}]

Sorting, as expected, puts zeros on the top. Even if I add logic to sort zeros towards the end:

array.sort((a,b) => {
    if (a.val === 0 || b.val === 0) return 1;
    return a.val < b.val;
});
Share Improve this question edited Jun 19, 2018 at 16:59 Latika Agarwal 9691 gold badge6 silver badges11 bronze badges asked Jun 19, 2018 at 16:32 d-_-bd-_-b 23.2k43 gold badges171 silver badges284 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 9

If a.val is 0, return 1. If b.val is 0, return -1

var array = [{val: 0}, {val: 1}, {val: 0}, {val: 3}];

array.sort((a, b) => {
  if (a.val === 0) return 1;        //Return 1 so that b goes first
  if (b.val === 0) return -1;       //Return -1 so that a goes first
  return a.val - b.val;
});

console.log(array);

You could check for zero and move this values to bottom, then sort by value.

var array = [{ val: 0 }, { val: 1 }, { val: 0 }, { val: 3 }];

array.sort((a, b) => (a.val === 0) - (b.val === 0) || a.val - b.val);

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Simply filter out zero and non-zero array, sort non zero array and concat both.

Try the following:

var arr = [{
    val: 0
}, {
    val: 1
}, {
    val: 0
}, {
    val: 3
}];
var nonZero = arr.filter((a)=>a.val !== 0);
var zeroArray = arr.filter((a)=>a.val === 0);
nonZero.sort((a,b)=>(a.val -b.val));
arr = nonZero.concat(zeroArray);
console.log(arr);

Define the parator. In case that the element is 0, it will be considered as larger. You cannot return 1 for both a ==0 and b==0.

发布评论

评论列表(0)

  1. 暂无评论