Skip to content

Instantly share code, notes, and snippets.

@roshanca
Last active April 10, 2017 03:16
Show Gist options
  • Save roshanca/f4bb0325b7b2938684146322988b55ad to your computer and use it in GitHub Desktop.
Save roshanca/f4bb0325b7b2938684146322988b55ad to your computer and use it in GitHub Desktop.
Array<Object> 根据 key 值进行排序 #tag: array, sort
const arr = [
{"name": "Kate", "age": 22},
{"name": "Candy", "age": 21},
{"name": "Petty", "age": 20}
];
arr.sort(compare('name')) // {"name": "Candy", "age": 21}, {"name": "Kate", "age": 22}, {"name": "Petty", "age": 20}
arr.sort(compare('age')); // {"name": "Petty", "age": 20}, {"name": "Candy", "age": 21}, {"name": "Kate", "age": 22}
function compare(key) {
return function(obj1, obj2) {
const value1 = obj1[key];
const value2 = obj2[key];
if (typeof value1 === 'number' && typeof value2 === 'number') {
if (value1 > value2) {
return 1;
} else if (value1 < value2) {
return -1;
} else {
return 0;
}
} else if (typeof value1 === 'string' && typeof value2 === 'string') {
return value1.localeCompare(value2);
} else {
throw Error('Compare value must be number or string.');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment