Last active
July 16, 2018 14:34
-
-
Save kaleem-elahi/8879db234afcef36dda103f97169ebaf to your computer and use it in GitHub Desktop.
A Sorting function that sorts Letters and Numbers both in ascending order (Made for React)
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
export function sortAll(arr, key = 'key', direction = 'asc', type = 'string') { | |
return arr.sort((a, b) => { | |
let keyA; | |
let keyB; | |
if (type === 'string') { | |
keyA = a[key].toLowerCase(); | |
keyB = b[key].toLowerCase(); | |
} | |
if (type === 'number') { | |
keyA = parseInt(a[key], 2); | |
keyB = parseInt(b[key], 2); | |
} | |
if (type === 'date') { | |
keyA = new Date(a[key]); | |
keyB = new Date(b[key]); | |
} | |
if (direction === 'desc') { | |
if (keyA < keyB) return 1; | |
if (keyA > keyB) return -1; | |
} else { | |
if (keyA < keyB) return -1; | |
if (keyA > keyB) return 1; | |
} | |
return 0; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment