admin管理员组文章数量:1310441
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
4 Answers
Reset to default 9If 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.
本文标签: javascriptSort an array of objects in ascending order but put all zeros at the endStack Overflow
版权声明:本文标题:javascript - Sort an array of objects in ascending order but put all zeros at the end - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741820943a2399360.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论