Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,939 questions

51,876 answers

573 users

How to sort an array of objects alphabetically in JavaScript

1 Answer

0 votes
const users = [
  { name: 'ccc', id: 4656 },
  { name: 'DDD', id: 3467 },
  { name: 'aaa', id: 9871 },
  { name: 'BBB', id: 5691 },
  { name: 'bbb', id: 7890 },
  { name: 'aaa', id: 1234 },
  { name: 'CCC', id: 0984 }  
];
 

const sortedobj = users.sort(function(a, b) {
  var sA = a.name.toUpperCase(); 
  var sB = b.name.toUpperCase(); 
  if (sA < sB) {
    return -1; 
  }
  if (sA > sB) {
    return 1; 
  }
  return 0;  
});

console.log(sortedobj)
     
     
     
/*
run:
     
[{
  id: 9871,
  name: "aaa"
}, {
  id: 1234,
  name: "aaa"
}, {
  id: 5691,
  name: "BBB"
}, {
  id: 7890,
  name: "bbb"
}, {
  id: 4656,
  name: "ccc"
}, {
  id: 984,
  name: "CCC"
}, {
  id: 3467,
  name: "DDD"
}]
     
*/

 



answered May 24, 2021 by avibootz

Related questions

...