Skip to content

Instantly share code, notes, and snippets.

@qdouble
Last active September 1, 2016 11:24
Show Gist options
  • Save qdouble/86f52076b62e9fcce776cfe04307c00a to your computer and use it in GitHub Desktop.
Save qdouble/86f52076b62e9fcce776cfe04307c00a to your computer and use it in GitHub Desktop.
Sorting observable with combine latest and sort function
const sortOther = function (a, b, sortBy, reverse) {
let nameA = a[sortBy];
let nameB = b[sortBy];
if (reverse) {
nameA = b[sortBy];
nameB = a[sortBy];
}
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
if (nameA === undefined) {
return -1;
}
// names must be equal
return 0;
};
const sortString = function (a, b, sortBy, reverse) {
let nameA;
let nameB;
a[sortBy] ? nameA = a[sortBy].toUpperCase() : nameA = a[sortBy];
b[sortBy] ? nameB = b[sortBy].toUpperCase() : nameB = b[sortBy];
if (reverse) {
b[sortBy] ? nameA = b[sortBy].toUpperCase() : nameA = b[sortBy];
a[sortBy] ? nameB = a[sortBy].toUpperCase() : nameB = a[sortBy];
}
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
};
export function combineSort <T>(sortBy: string | number, obj) {
return obj.sort(function (a, b) {
if (!a || !b) return obj;
if (typeof a[sortBy[0]] === 'string') return sortString(a, b, sortBy[0], sortBy[1]);
return sortOther(a, b, sortBy[0], sortBy[1]);
});
};
this.sortedArray$ = Observable.combineLatest(
[sortbyVar, reverseVar], this.unsortedArray$, combineSort
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment