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!!!
Using lodash, you can easily solve the problem: use Lodash to sort array of object by value
_.sortBy(myArray, o => o.name.toLowerCase())
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) }));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.