Skip to content

Instantly share code, notes, and snippets.

@komkanit
Last active September 22, 2017 16:52
Show Gist options
  • Save komkanit/7a24d26466257afc04b62c1c50922fc5 to your computer and use it in GitHub Desktop.
Save komkanit/7a24d26466257afc04b62c1c50922fc5 to your computer and use it in GitHub Desktop.
var data = [
{
"firstname": "สมยศ",
"address": "3",
"district": "โชคเหนือ",
"amphoe": "ลำดวน",
"province": "สุรินทร์"
},
{
"firstname": "บุญหนา",
"address": "2",
"district": "อู่โลก",
"amphoe": "ลำดวน",
"province": "สุรินทร์"
},
{
"firstname": "สมดี",
"address": "1",
"district": "บ้านตาด",
"amphoe": "บ้านดุง",
"province": "อุดรธานี"
},
]
const compare = (a, b, keys) => (
keys.reduce((data, key) => {
if(data === 0 && a[key] !== b[key]) {
if (!isNaN(a[key]) && !isNaN(b[key])) {
data = a[key] - b[key];
} else {
data = (a[key] < b[key]) ? -1 : 1;
}
}
return data;
}, 0)
);
const keys = ['province','amphoe','district','address','firstname']
data.sort((a, b) => compare(a, b, keys));
console.log(data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment