I have a challenge in JavaScript that I’m trying to figure out for a while already.
Consider this array:
let arr = [0, 1, 0, 2, 0, 3, 0, 4, 0, 5];
I have to output this result:
arr = [0, 0, 0, 0, 0, 5, 4, 3, 2, 1]
I’m following this line of logic to position the zeros in front, adjusting the index value:
arr.sort((x, y) => {
if (x !== 0) {
return 1;
}
if (x === 0) {
return -1;
}
return y - x;
});
But I’m stuck at this result:
arr = [0, 0, 0, 0, 0, 1, 2, 3, 4, 5]
Does anyone have any tips on how to solve this?