Last active
September 5, 2020 09:06
-
-
Save RolandWarburton/0544249b1c5757bb0a505e22d71070ed to your computer and use it in GitHub Desktop.
sorting int arrays in javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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