Skip to content

Instantly share code, notes, and snippets.

@lancevo
Created January 24, 2019 05:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lancevo/99e84110314a4e1d587067dca268a300 to your computer and use it in GitHub Desktop.
Save lancevo/99e84110314a4e1d587067dca268a300 to your computer and use it in GitHub Desktop.
Sort Objects

Objects Sorter:

Sort objects by property name. It detects property type such as number, string, and date and sort them properly.

Usage

var models = [
      {name: "john", level: 42, dob: "01/12/1940"},
      {name: "joe", level: 12, dob: "01/12/1941"},
      {name: "amber", level: 50, dob: "02/2/2001"}
    ];

// cache the sort fn, and sort by name
var sortFnCache = sortProp('name');
models.sort(sortFnCache);

See demo (in console) http://jsfiddle.net/lvo811/dWvS7/

/*
source: https://github.com/lancevo/object-sorter
sort objects property,
usage:
arrObjs.sort(sortProp(propertyName, false));
see demo (in console):
http://jsfiddle.net/lvo811/dWvS7/
*/
var sortProp = function (name, descending) {
var descending = descending || false ? -1 : 1;
return function (objA, objB) {
var flag = 0,
a = objA[name],
b = objB[name];
if (typeof a == "number" && typeof b == "number") {
flag = a - b;
} else if ((typeof a == "string") && a.match(/^\d{1,2}\/\d{1,2}\/(\d{2}|\d{4})$/)) {
flag = new Date(a) < new Date(b) ? -1 : 1;
} else {
// assume it's a string
flag = a < b ? -1 : 1;
}
return descending * flag;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment