Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array of objects by string property value

I have an array of JavaScript objects:

var objs = [      { first_nom: 'Lazslo', 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?

like image 435
Tyrone Slothrop Avatar asked Jul 15 '09 03:07

Tyrone Slothrop


People also ask

How do you sort an array of objects by string?

To sort an array of objects, use the sort() method with a compare function. A compareFunction applies rules to sort arrays by defined our own logic. They allow us to sort arrays of objects by strings, integers, dates, or any other custom property.

How do you sort an array of objects based on the key?

const arr1 = ['d','a','b','c'] ; const arr2 = [{a:1},{c:3},{d:4},{b:2}]; We are required to write a JavaScript function that accepts these two arrays. The function should sort the second array according to the elements of the first array.

Can you sort an array of objects in JavaScript?

Sort an Array of Objects in JavaScriptTo sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.


1 Answers

It's easy enough to write your own comparison function:

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 ); 

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)) 
like image 90
Wogan Avatar answered Sep 22 '22 15:09

Wogan