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?

3
  • 2
    You don't have to use lodash, you can just use the native Array.prototype.sort function. Commented Jun 23, 2016 at 14:14
  • lodash.com/docs#sortBy Commented Jun 23, 2016 at 14:15
  • if you want pure js way see answer Commented Jun 23, 2016 at 14:16

4 Answers 4

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

Name is the sort key here

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

2 Comments

Thanks! This is way easier to read and understand than the normal JavaScript way
Btw I also just figured out that this works: namesArray = _.orderBy(res, ['name'], ['asc', 'desc']);
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);

Comments

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/

3 Comments

@NinaScholz I used assignment because I have different variable names. But sure without is fine also.
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.
@LeonGaban no prob. Keep in mind that adding lodash to do such simple task might be overkill and slowing down your app.
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

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.