Skip to content

Instantly share code, notes, and snippets.

@ahamed
Created February 2, 2021 16:03
Show Gist options
  • Select an option

  • Save ahamed/adf8cac6d0c6d6bf283505b5087a58d0 to your computer and use it in GitHub Desktop.

Select an option

Save ahamed/adf8cac6d0c6d6bf283505b5087a58d0 to your computer and use it in GitHub Desktop.
Sort integer array using javascript native method.
/**
* The behavior of JavaScript sort method on integer array.
*
* @author Sajeeb Ahamed <sajeeb07ahamed@gmail.com>
*/
const arr = [3, 4, 2, 100, 98, 34];
arr.sort();
/**
* Output: [100, 2, 3, 34, 4, 98]
* weird, isn't it?
* This is because JavaScript consider the elements as string and sort them lexicographically.
* That is, match the first digit then second digit and so on and sort accordingly.
*/
console.log(arr); // [100, 2, 3, 34, 4, 98]
// Then how to sort what are we wanting?
arr.sort((a, b) => a - b);
console.log(arr); // Output: [2, 3, 4, 34, 98, 100]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment