Skip to content

Instantly share code, notes, and snippets.

@danutzcodrescu
Last active July 6, 2018 12:14
Show Gist options
  • Save danutzcodrescu/ef8f19d94c78cf36facbb7bc6fe8f32e to your computer and use it in GitHub Desktop.
Save danutzcodrescu/ef8f19d94c78cf36facbb7bc6fe8f32e to your computer and use it in GitHub Desktop.
sorting methods for a javascript objects array
import { isString } from "util";
export function sort(data, order, column) {
return data.sort((a, b) => {
const first = isString(a[column]) ? a[column].toLowerCase() : a[column];
const second = isString(b[column]) ? b[column].toLowerCase() : b[column];
if (order === "asc") {
if (first < second) {
return -1;
} else if (first > second) {
return 1;
} else {
return 0;
}
} else {
if (first > second) {
return -1;
} else if (first < second) {
return 1;
} else {
return 0;
}
}
});
}
const collator = new Intl.Collator(undefined, {
numeric: true,
sensitivity: "variant"
});
export function sortWithCollator(data, order, column) {
const sorted = data.sort((a, b) => {
return collator.compare(a[column], b[column]);
});
if (order === "desc") sorted.reverse();
return sorted;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment