How to sort array of objects by first string property value in JavaScript

1 Answer

0 votes
function compare(a, b) {
  if (a.first_s < b.first_s) {
    return -1;
  }
  if (a.first_s > b.first_s) {
    return 1;
  }
  return 0;
}

var obj_arr = [ 
    {first_s: 'bbb', last_s: 'yyy'},
    {first_s: 'ccc', last_s: 'zzz'},
    {first_s: 'aaa', last_s: 'xxx'}
];

obj_arr.sort(compare);

console.log(obj_arr); 

  
    
    
/*
run:
    
[{
  first_s: "aaa",
  last_s: "xxx"
}, {
  first_s: "bbb",
  last_s: "yyy"
}, {
  first_s: "ccc",
  last_s: "zzz"
}]
    
*/

 



answered Dec 12, 2020 by avibootz
...