0

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?

Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
Leon Gaban
  • 36,509
  • 115
  • 332
  • 529
  • 2
    You don't have to use lodash, you can just use the native [Array.prototype.sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) function. – Pointy Jun 23 '16 at 14:14
  • https://lodash.com/docs#sortBy – Jack Jun 23 '16 at 14:15
  • if you want pure js way see [answer](http://stackoverflow.com/questions/16648076/sort-array-on-key-value) – Callum Linington Jun 23 '16 at 14:16

4 Answers4

1
_.sortBy(myObjects, 'name');

Name is the sort key here

Piyush.kapoor
  • 6,715
  • 1
  • 21
  • 21
1

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/

Sergio
  • 28,539
  • 11
  • 85
  • 132
  • @NinaScholz I used assignment because I have different variable names. But sure without is fine also. – Sergio Jun 23 '16 at 14:20
  • 1
    Thanks! +1, the reason I was looking for a lodash solution, is because their API is so much easier to reason about quickly by other devs. – Leon Gaban Jun 23 '16 at 14:23
  • @LeonGaban no prob. Keep in mind that adding lodash to do such simple task might be overkill and slowing down your app. – Sergio Jun 23 '16 at 14:25
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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

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

brk
  • 48,835
  • 10
  • 56
  • 78