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?
The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
The descending order of numbers can be found by subtracting 1 from the number. For example, to write 10 to 6 in descending order, we will start with the largest number in the above sequence, which is 10 and keep subtracting 1 from it until we reach the lowest number.
Method 1 : Sort Binary Array By Counting ZeroesStep 1 : Count number of 0s in the given inputArray . Let it be zeroCount . Step 2 : Rewrite inputArray with 0s from 0 to zeroCount . Step 3 : Rewrite remaining places with 1s.
Ascending means going up, so an ascending sort will arrange numbers from smallest to largest and text from A to Z. Descending means going down, or largest to smallest for numbers and Z to A for text.
You could sort by the delta of b
and a
(for descending sorting) and take Number.MAX_VALUE
, for falsy values like zero.
This:
Number.MAX_VALUE - Number.MAX_VALUE
is equal to zero.
let array = [0, 1, 0, 2, 0, 3, 0, 4, 0, 5]; array.sort((a, b) => (b || Number.MAX_VALUE) - (a || Number.MAX_VALUE)); console.log(...array);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With