简体   繁体   中英

How to sort Array by alpha of a specific key inside each object?

Example of my Array =

[{
    name: leon,
    id: 1
}, {
    name: laura
    id: 20003
}, {
    name: anne
    id: 45
}]

Currently in the UI, the array will look like:

  • leon
  • laura
  • anne

How can one use lodash to sort the array by the name keys in alphabetical order?

_.sortBy(myObjects, 'name');

名称是此处的排序键

You do not need lodash to do that...

Just do

var sortedNames = names.sort(function(a, b) {
  return a.name.localeCompare(b.name);
});

jsFiddle: https://jsfiddle.net/p07c4oaa/

Or wrap that in a function like:

function sortBy(obj, key) {
  return obj.sort(function(a, b) {
    return a[key].localeCompare(b[key]);
  });
}

jsFiddle: https://jsfiddle.net/p07c4oaa/1/

You could use a proper callback.

 var array = [{ name: 'leon', id: 1}, { name: 'laura', id: 20003}, { name: 'anne', id: 45}]; array.sort(function (a, b) { return a.name.localeCompare(b.name); }); console.log(array); 

Not sure of loadash but you can use simple sort method to sort the json array of objects

var arry=[{
    name: 'leon',
    id: 1
}, {
    name: 'laura',
    id: 20003
}, {
    name: 'anne',
    id: 45
}]
var sorted = arry.sort(function(a,b){
return a.name > b.name ? 1:-1
})
// this part just for demo

sorted.forEach(function(item){
document.write('<pre>'+item.name+'</pre>')

})

JSFIDDLE

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM