Underscore.js _.sortBy Function
The _.sortBy() function is used to sort all the elements of the list in ascending order according to the function given to it as a parameter. Passing the array with a function which returns the number and it will sort the array in ascending order and return an array. The array can be both of numeric values and string values.
_.sortBy(list, iteratee, [context])
Parameters: This function accepts three parameters as mentioned above and described below:
- List: This parameter is used to set the list of items.
- Iteratee: 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.
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.
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.
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.
You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.