- Spec files
npm-lodash
Describes: pkg:npm/lodash@4.7.x
- Description
- A modern JavaScript utility library delivering modularity, performance, & extras
- Author
- tessl
- Last updated
index.md docs/
1# Lodash23Lodash is a modern JavaScript utility library delivering modularity, performance, and extras. This Knowledge Tile focuses on the `_.sortBy` method, which creates an array of elements sorted in ascending order by the results of running each element in a collection through each iteratee. This method performs a stable sort, preserving the original sort order of equal elements.45## Package Information67- **Package Name**: lodash8- **Package Type**: npm9- **Language**: JavaScript10- **Installation**: `npm install lodash`1112## Core Imports1314```javascript15const _ = require('lodash');16const sortBy = _.sortBy;17```1819For ES modules:2021```javascript22import _ from 'lodash';23import { sortBy } from 'lodash';24```2526## Basic Usage2728```javascript29const _ = require('lodash');3031const users = [32{ 'user': 'fred', 'age': 48 },33{ 'user': 'barney', 'age': 36 },34{ 'user': 'fred', 'age': 40 },35{ 'user': 'barney', 'age': 34 }36];3738// Sort by user name using function iteratee39const sortedByUser = _.sortBy(users, function(o) { return o.user; });40// => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]4142// Sort by property name using string shorthand43const sortedByAge = _.sortBy(users, 'age');44// => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]4546// Sort by multiple criteria47const sortedMultiple = _.sortBy(users, ['user', 'age']);48// => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]49```5051## Capabilities5253### Sort By Function5455Creates an array of elements, sorted in ascending order by the results of running each element in a collection through each iteratee.5657```javascript { .api }58/**59* Creates an array of elements, sorted in ascending order by the results of60* running each element in a collection through each iteratee. This method61* performs a stable sort, that is, it preserves the original sort order of62* equal elements. The iteratees are invoked with one argument: (value).63*64* @static65* @memberOf _66* @since 0.1.067* @category Collection68* @param {Array|Object} collection The collection to iterate over.69* @param {...(Array|Array[]|Function|Function[]|Object|Object[]|string|string[])} [iteratees=[_.identity]]70* The iteratees to sort by, specified individually or in arrays.71* @returns {Array} Returns the new sorted array.72*/73function sortBy(collection, ...iteratees)74```7576**Parameters:**7778- `collection` *(Array|Object)*: The collection to iterate over79- `...iteratees` *(...(Array|Array[]|Function|Function[]|Object|Object[]|string|string[]))*: The iteratees to sort by, specified individually or in arrays8081**Returns:**8283*(Array)*: Returns the new sorted array8485**Key Features:**8687- **Stable Sort**: Preserves the original sort order of equal elements88- **Multiple Iteratees**: Supports sorting by multiple criteria89- **Flexible Iteratees**: Accepts functions, property shortcuts, or object matchers90- **Null/Undefined Handling**: Moves `null`, `undefined`, and `NaN` values to the end91- **Object Collections**: Works with both arrays and objects as collections92- **Empty Collection Handling**: Returns empty array for `null`, `undefined`, or numeric collections9394**Usage Examples:**9596```javascript97const _ = require('lodash');9899// Function iteratee100_.sortBy(users, function(o) { return o.user; });101102// Property shorthand103_.sortBy(users, 'age');104105// Multiple criteria (array of iteratees)106_.sortBy(users, ['user', 'age']);107108// Mixed iteratees109_.sortBy(users, 'user', function(o) {110return Math.floor(o.age / 10);111});112113// No iteratee (uses identity function)114_.sortBy([3, 2, 1]); // => [1, 2, 3]115116// Object as collection117_.sortBy({ 'a': 1, 'b': 2, 'c': 3 }, Math.sin); // => [3, 1, 2]118119// Handling special values120_.sortBy([NaN, undefined, null, 4, null, 1, undefined, 3, NaN, 2]);121// => [1, 2, 3, 4, null, null, undefined, undefined, NaN, NaN]122123// Arrays returned from iteratee are coerced124const objects = [125{ 'a': 'x', 'b': 3 },126{ 'a': 'y', 'b': 4 },127{ 'a': 'x', 'b': 1 },128{ 'a': 'y', 'b': 2 }129];130_.sortBy(objects, function(object) {131var result = [object.a, object.b];132result.toString = function() { return String(this[0]); };133return result;134});135136// Works as iteratee for other methods137[[2, 1, 3], [3, 2, 1]].map(_.sortBy); // => [[1, 2, 3], [1, 2, 3]]138```139140**Error Handling:**141142- Returns `[]` when collection is `null` or `undefined`143- Treats numeric values for collection as empty and returns `[]`144- Places `null`, `undefined`, and `NaN` values at the end of sorted results145- Falls back to identity function when iteratee is nullish146147**Performance Characteristics:**148149- Time complexity: O(n log n) where n is the collection size150- Stable sort algorithm preserves relative order of equal elements151- Creates a new array rather than modifying the input collection152- Uses efficient internal sorting with compareMultiple for multiple criteria