snippetjavascriptCritical
Sort array of objects by string property value
Viewed 0 times
arraypropertysortobjectsvaluestring
Problem
I have an array of JavaScript objects:
How can I sort them by the value of
I know about
var objs = [
{ first_nom: 'Laszlo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];How can I sort them by the value of
last_nom in JavaScript?I know about
sort(a,b), but that only seems to work on strings and numbers. Do I need to add a toString() method to my objects?Solution
It's easy enough to write your own comparison function:
Or inline (c/o Marco Demaio):
Or simplified for numeric (c/o Andre Figueiredo):
function compare( a, b ) {
if ( a.last_nom b.last_nom ){
return 1;
}
return 0;
}
objs.sort( compare );Or inline (c/o Marco Demaio):
objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0))
Or simplified for numeric (c/o Andre Figueiredo):
objs.sort((a,b) => a.last_nom - b.last_nom); // b - a for reverse sort
Code Snippets
function compare( a, b ) {
if ( a.last_nom < b.last_nom ){
return -1;
}
if ( a.last_nom > b.last_nom ){
return 1;
}
return 0;
}
objs.sort( compare );Context
Stack Overflow Q#1129216, score: 5803
Revisions (0)
No revisions yet.