Last active
April 10, 2017 03:16
-
-
Save roshanca/f4bb0325b7b2938684146322988b55ad to your computer and use it in GitHub Desktop.
Array<Object> 根据 key 值进行排序 #tag: array, sort
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
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