Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting using JavaScript's sort method

I am studying javascript sort method.
So, I want to sort using only sort without filter or map or otherMethod function.

const arr = [1,100,3,5,7,3,2,7, -1]

In the above array, I want the numbers greater than 5 to be sorted first, followed by the smaller numbers in ascending order.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Expected results are:
// [5, 7, 7, 100, -1, 1, 2, 3, 3];

Again, I know how to sort using other methods!

for example

const arr1 = input.filter(num => num >= 5).sort((a, b) => a - b)
const arr2 = input.filter(num => num < 5).sort((a,b) => a - b)

[...arr1, ...arr2]

But I hope to solve it using only the sort method!

please help me

arr.sort((a,b) => {
  return (a+5) > b ? 1 : -1
})

but result is : 
// [1, 3, -1, 5, 2, 7, 3, 7, 100]

>Solution :

First return the difference between whether one value or the other is less than 5 – proceed to sort numerically (with subtraction) only if that difference is 0 (in which case both values being compared are 5 or above, or both values are less than 5).

const arr = [1,100,3,5,7,3,2,7, -1];
arr.sort((a, b) => 
  ((b >= 5) - (a >= 5))
  || a - b
);
console.log(arr);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading