0

I get this code from a basic javascript lesson on Codewar, but I don't understand how it work, I tried one by one condition but it doesn't show output as I expected. Thank you so much.

var arr=[1,2,3,4,5,6,100,999]
arr.sort((a,b)=>{
  if (a%2==b%2) return a-b;
  if (a%2>b%2) return -1;
  return 1;
})
console.log(arr)

//output: [ 1, 3, 5, 999, 2, 4, 6, 100 ]
2
  • 1
    Well, what output did you expect? Commented Dec 8, 2017 at 19:00
  • Because I don't understand it so I saw it a little strange. Now I got it. Commented Dec 9, 2017 at 2:50

1 Answer 1

1

it should print the odd numbers first then even numbers, each is sorted

if (a%2==b%2) return a-b; if a, b are both even or both odd then sort them in increasing order

if (a%2>b%2) return -1; else if they are different [ one odd and the other is even ] put the odd numbers first

else a, b are equal

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

1 Comment

Thank u for your explaination. I help me understood how it works.

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.