Last active
August 29, 2015 14:18
-
-
Save leeferwagen/ac56b34b0ff5f10e86eb to your computer and use it in GitHub Desktop.
Sorting of array containing objects
This file contains hidden or 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
(function(scope) { | |
function cmp(a, b, mul) { | |
return (a == b ? 0 : (a < b ? -1 : 1)) * mul; | |
} | |
function ocmp() { | |
var _sorting = [].slice.call(arguments).filter(function(v) { | |
return v != null; | |
}).map(function(v) { | |
if (typeof v == 'string') { | |
return {key: v, mul: 1}; | |
} else { | |
return {key: v[0], mul: v[1]}; | |
} | |
}); | |
return function(a, b) { | |
return _sorting.reduce(function(mem, sort) { | |
return mem - cmp(a[sort.key], b[sort.key], sort.mul); | |
}, 0); | |
}; | |
} | |
scope.ocmp = ocmp; | |
}(window)); | |
var a = [ | |
{name: 'aaa', age: 11, uid: 44, desc: 'obj-1'}, | |
{name: 'aaa', age: 10, uid: 55, desc: 'obj-2'}, | |
{name: 'bbb', age: 20, uid: 22, desc: 'obj-3'}, | |
{name: 'bbb', age: 19, uid: 66, desc: 'obj-4'}, | |
]; | |
console.log(a.sort(ocmp('uid', 'age'))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment