Underscore.js _.sortBy Function
_.sortBy(list, iterate, [context])
Parameters: This function accepts three parameters as mentioned above and described below:
- List: This parameter is used to set the list of items.
- Iterate: This parameter is used to hold the test condition.
- Context: This parameter is used to display the content.
Return values: It returns a sorted array which is being sorted according to the function passed. Using a function which simply returns a number: The ._sortBy() function takes the element from the list one by one and do the specified operations given in the function. Like here the function is just to sort all the elements of the list. After traversing and sorting all the elements, the sortBy() function ends. Now, the variable which stores the original array will contain the sorted array. Example:
Output: Using Math.cos() function: Passing a list of numbers and do operations like taking ‘cos()’ of the numbers and then comparing them to sort the array. In the same manner apply all the “math’ function like tan(), sin(), cot() etc to sort the array. Example:
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’. Console.log the sorted array by passing the array and that property. Example:
Output: Reversing an array using _.sortBy() function: Although, the _.sortBy() function sorts in an ascending order but still reverse the array with the help of yet another function ‘reverse()’ along with _.sortBy(). First, _.sortBy() function will sort the list in ascending order and then the ‘reverse()’ function will make the array reversed. Finally, print the array. Example: