1

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]
1
  • Your sort callback needs to do the following: if both a and b are both below 5 or above 5, return -1 or 1 depending on which number is greater. If one number of below 5 and the other above 5, return -1 or 1 depending on which number is below/above 5. Commented Nov 9, 2022 at 1:07

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.