Skip to content

Instantly share code, notes, and snippets.

@daltonmenezes
Last active March 30, 2020 01:56
Show Gist options
  • Save daltonmenezes/e4c09a40b5389564eedf7976edb54abc to your computer and use it in GitHub Desktop.
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
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