Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting numbers in descending order but with `0`s at the start

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?

like image 514
lianbwl Avatar asked Nov 19 '19 12:11

lianbwl


People also ask

How do you sort in descending order?

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.

How do you list numbers in descending order?

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.

How do you sort an array of zeros and ones?

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.

Is descending order A to Z or Z to A?

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.


1 Answers

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);
like image 82
Nina Scholz Avatar answered Oct 14 '22 07:10

Nina Scholz