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.
- jQuery | after() with Examples
- Underscore.js | _.zip() with Examples
- Underscore.js | _.without() with Examples
- Underscore.js | where() with Examples
- jQuery | on() with Examples
- jQuery | first() with Examples
- jQuery | one() with Examples
- Underscore.js | map() with Examples
- jQuery | last() with Examples
- Underscore.js | min() with Examples
- Underscore.js | max() with Examples
- jQuery | eq() with Examples
- jQuery | val() with Examples
- Underscore.js | first() with Examples
- Underscore.js | every() with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.