0

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!!!

2 Answers 2

1

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)
}));

Sign up to request clarification or add additional context in comments.

1 Comment

@RehanShah You're welcome!
1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.