Rehan Shah
Rehan Shah

Reputation: 1627

sort whole object with specific (key->value) in JavaScript alphabetically?

I have an array in JavaScript that looks like

[
   {
      "name":"a",
      "phoneNo":"1"
   },
   {
      "name":"X",
      "phoneNo":"3"
   },
   {
      "name":"A",
      "phoneNo":"2"
   },
   {
      "name":"b",
      "phoneNo":"4"
   },
   {
      "name":"c",
      "phoneNo":"5"
   },
   {
      "name":"D",
      "phoneNo":"6"
   }
]

and I want to sort it by the name value in each array, alphabetically. NOTE: all name will be converted to lowercase first. I am stuck with this problem and I tried alot to solve it myself and also tried some research but I did'nt found something. Help!!!

Upvotes: 0

Views: 36

Answers (2)

Naren Murali
Naren Murali

Reputation: 56650

Solution using JS

Reference here

const arr = [
   {
      "name":"a",
      "phoneNo":"1"
   },
   {
      "name":"X",
      "phoneNo":"3"
   },
   {
      "name":"A",
      "phoneNo":"2"
   },
   {
      "name":"b",
      "phoneNo":"4"
   },
   {
      "name":"c",
      "phoneNo":"5"
   },
   {
      "name":"D",
      "phoneNo":"6"
   }
]

console.log(arr.sort(function(a, b){
 var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase();
 if (nameA < nameB) //sort string ascending
  return -1;
 if (nameA > nameB)
  return 1;
 return 0; //default return value (no sorting)
}));

Upvotes: 1

ch271828n
ch271828n

Reputation: 17587

Using lodash, you can easily solve the problem: use Lodash to sort array of object by value

_.sortBy(myArray, o => o.name.toLowerCase())

Upvotes: 1

Related Questions