How to sort array of objects by one string property value in descending order JavaScript

1 Answer

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

var workers = [
    { id: 13451, name: 'Axel'},
    { id: 39810, name: 'Isla'},
    { id: 87134, name: 'Blaze'},
    { id: 79372, name: 'Dexter'}
];


workers.sort(compare);

console.log(workers);




/*
run:

[
  { id: 39810, name: 'Isla' },
  { id: 79372, name: 'Dexter' },
  { id: 87134, name: 'Blaze' },
  { id: 13451, name: 'Axel' }
]

*/

 



answered Jun 17, 2020 by avibootz
...