Skip to content

Instantly share code, notes, and snippets.

@RolandWarburton
Last active September 5, 2020 09:06
Show Gist options
  • Save RolandWarburton/0544249b1c5757bb0a505e22d71070ed to your computer and use it in GitHub Desktop.
Save RolandWarburton/0544249b1c5757bb0a505e22d71070ed to your computer and use it in GitHub Desktop.
sorting int arrays in javascript
const a = 9999
const b = 100
const arr = [9999,100]
// sort function
const res = (a, b) => {return a-b}
// "sort" 2 numbers on their own returns the result from the subtraction
console.log(res(a,b))
// returns -9899
// Same applied to arrays
console.log(res(arr[0], arr[1]))
// returns 1
// testing the same above but using the sort method
// This changes how res() acts and now it uses it as a comparison
// a-b=negative = return a
// a-b=positive = return b
const sorted = arr.sort((a,b) => {return res(a,b)})
console.log(sorted)
// returns [100,9999]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment