Home > Back-end >  Sorting using JavaScript's sort method
Sorting using JavaScript's sort method

Time:11-09

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.

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]

CodePudding user response:

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);

  • Related