WebMasterCampus
WEB DEVELOPER Resources

Javascript Sort of Array Objects by String Property Value

Learn how to use javascript to Sort of an array objects by string property value


Javascript Sort of Array Objects by String Property Value

To sort an array of objects by a property value in JavaScript. We can use the sort() method of Array. Arrays of objects can be sorted by comparing the value of one of their properties.

var objs = [ 
    { first_name: 'Peter',   last_name: 'Hall'     },
    { first_name: 'Roger',   last_name: 'Foster'   },
    { first_name: 'Amy',    last_name: 'sister' }
];

function compareLastName( a, b ) {
  if ( a.last_name < b.last_name ){
    return -1;
  }
  if ( a.last_name > b.last_name ){
    return 1;
  }
  return 0;
}

function compareFirstName( a, b ) {
  if ( a.first_name < b.first_name ){
    return -1;
  }
  if ( a.first_name > b.first_name ){
    return 1;
  }
  return 0;
}


console.log( objs.sort( compareLastName ) );
console.log( objs.sort( compareFirstName ) );
Created with love and passion.