Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

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?

1 Answer

0 votes
by (106k points)
edited by

You can sort an array of objects by string property value by using the below-mentioned code:-

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

If you are passionate to pursue a career in Web Development, you can take up Web Development training by Intellipaat! 

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...