Last active
September 15, 2021 14:22
-
-
Save nathansmith/5811250 to your computer and use it in GitHub Desktop.
Function to sort an array of objects by a particular key's value.
This file contains 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 sort_by_key_value(arr, key) { | |
var to_s = Object.prototype.toString; | |
var valid_arr = to_s.call(arr) === '[object Array]'; | |
var valid_key = typeof key === 'string'; | |
if (!valid_arr || !valid_key) { | |
return; | |
} | |
arr = arr.slice(); | |
return arr.sort(function(a, b) { | |
var a_key = String(a[key]); | |
var b_key = String(b[key]); | |
var n = a_key - b_key; | |
return !isNaN(n) ? n : a_key.localeCompare(b_key); | |
}); | |
} | |
/* | |
Used like this... | |
*/ | |
var old_arr = [ | |
{ | |
test: 'betty' | |
}, | |
{ | |
test: 2 | |
}, | |
{ | |
test: 'alfred' | |
}, | |
{ | |
test: 'Chris' | |
}, | |
{ | |
test: 1 | |
}, | |
{ | |
test: 'Betty' | |
}, | |
{ | |
test: 3 | |
}, | |
{ | |
test: 'Alfred' | |
}, | |
{ | |
test: 'chris' | |
} | |
]; | |
var new_arr = sort_by_key_value(old_arr, 'test'); | |
new_arr.forEach(function(item) { | |
console.log(item.test); | |
}); | |
/* | |
Returns... | |
[ | |
{ | |
test: 1 | |
}, | |
{ | |
test: 2 | |
}, | |
{ | |
test: 3 | |
}, | |
{ | |
test: 'alfred' | |
}, | |
{ | |
test: 'Alfred' | |
}, | |
{ | |
test: 'betty' | |
}, | |
{ | |
test: 'Betty' | |
}, | |
{ | |
test: 'chris' | |
}, | |
{ | |
test: 'Chris' | |
} | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
UPDATE
Courtesy of a coworker, you could do this in Underscore (or Lo-Dash) by passing a custom iterator function.
That gets 99% there, except that lowercase variations of words don't necessarily precede their uppercase counterparts…
http://cl.ly/image/272e2h0R0512
Note:
"alfred"
precedes"Alfred"
and"betty"
precedes"Betty"
, yet"Chris"
precedes"chris"
.