TheWebs
TheWebs

Reputation: 12923

Using underscore to sort nested objects in an array

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?

Upvotes: 6

Views: 4629

Answers (1)

thefourtheye
thefourtheye

Reputation: 239443

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);

Upvotes: 15

Related Questions