Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 889
TheWebs Avatar asked Oct 02 '15 15:10

TheWebs


People also ask

How do you access an array nested object?

A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.

How to use_ sortBy?

html. Output: Using a property of the array: Apply _. sortBy() method to strings and first declare the array (here array is 'arr'). Choose one property of the array on the basis of which need to sort like here 'name'.

How does sortBy work?

The SORTBY function sorts the contents of a range or array based on the values in a corresponding range or array. In this example, we're sorting a list of people's names by their age, in ascending order.

What does flatten do in js?

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.


1 Answers

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);
like image 156
thefourtheye Avatar answered Sep 28 '22 06:09

thefourtheye