javascript tutorial - [Solved-5 Solutions] Sort array of objects by string property value in javascript - javascript - java script - javascript array



Problem:

We 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' }
];
click below button to copy the code. By JavaScript tutorial team

How can we sort them by the value of last_nom in JavaScript ? we know about sort(a,b), but that only seems to work on strings and numbers. Do you need to add a toString method to my objects ?

Solution 1:

It's easy enough to write our 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);
click below button to copy the code. By JavaScript tutorial team

Or inline (c/o Marco Demaio):

objs.sort(function(a,b) {return (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) 
click below button to copy the code. By JavaScript tutorial team

Solution 2:

use underscore, its small and awesome...

sortBy_.sortBy(list, iterator, [context]) Returns a sorted copy of list, ranked in ascending order by the results of running each value through iterator. Iterator may also be the string name of the property to sort by (eg. length).

var objs = [ 
  { first_nom: 'Lazslo',last_nom: 'Jamf' },
  { first_nom: 'Pig', last_nom: 'Bodine'  },
  { first_nom: 'Pirate', last_nom: 'Prentice' }
];

var sortedObjs = _.sortBy( objs, 'first_nom' );
click below button to copy the code. By JavaScript tutorial team

Solution 3:

Don't get why people make it so complicated:

objs.sort(function(a, b){
  return a.last_nom > b.last_nom;
});
For stricter engines:
objs.sort(function(a, b){
  return a.last_nom == b.last_nom ? 0 : +(a.last_nom > b.last_nom) || -1;
});
click below button to copy the code. By JavaScript tutorial team

Swap the operator to have it sorted by reverse alphabetical order.

Solution 4:

In ES6/ES2015 or later we can do this way:

objs.sort((a, b) => a.last_nom.localeCompare(b.last_nom));
click below button to copy the code. By JavaScript tutorial team

Solution 5:

If we have duplicate last names we might sort those by first name-

obj.sort(function(a,b){
  if(a.last_nom< b.last_nom) return -1;
  if(a.last_nom >b.last_nom) return 1;
  if(a.first_nom< b.first_nom) return -1;
  if(a.first_nom >b.first_nom) return 1;
  return 0;
});
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Sort array of objects by string property value in javascript