6

Consider the following expanded object:

enter image description here

Now each of these objects is stored into an array and its easy to sort by name, email, created_at or what ever else. But what about if I wanted to sore by the users profile investor type. In the image you would do: data.profile.data.investor_type to get the investor type.

How do I use underscore to sort an array of these objects by nested attributes in the object?

2

1 Answer 1

15

You can use _.sortBy with the exact code you have show

_.sortBy(data, function(obj) { return obj.profile.data.investor_type; });

If your environment supports ECMA Script 2015's Fat-arrow functions, then you can write the same as

_.sortBy(data, (obj) => obj.profile.data.investor_type);
Sign up to request clarification or add additional context in comments.

5 Comments

I am a bit lost how will this sort the array of objects by the investor type in this case?
For every element in the array, corresponding investor_type is used for comparisons. So, the array of objects will be sorted based on the investor_type.
you definitely have to read the _.sortBy function as sort the array by the given value I specify, in your case "profile.data.investor_type". a fiddle entry to play : jsfiddle.net/zobidafly/g45pereL
@zobidafly Do you mean to say this solution will not work?
@thefourtheye : no, it works, I just added a comment and a link to check that it works...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.