Last active
March 30, 2020 01:56
-
-
Save daltonmenezes/e4c09a40b5389564eedf7976edb54abc to your computer and use it in GitHub Desktop.
Sorting numbers by ASC and DESC in javascript without mutating the original array
This file contains 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 numbers = [4, 2, 5, 1, 3] | |
const orderBy = ([...arr], type = 'ASC') => { | |
const order = { | |
ASC: (a, b) => a - b, | |
DESC: (a, b) => b - a | |
} | |
return arr.sort(order[type]) | |
} | |
console.log( | |
orderBy(numbers, 'ASC'), // [1, 2, 3, 4, 5] | |
orderBy(numbers, 'DESC'), // [5, 4, 3, 2, 1] | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment