Skip to content

Instantly share code, notes, and snippets.

@kaleem-elahi
Last active July 16, 2018 14:34
Show Gist options
  • Save kaleem-elahi/8879db234afcef36dda103f97169ebaf to your computer and use it in GitHub Desktop.
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)
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