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.