Research
Security News
Malicious npm Package Targets Solana Developers and Hijacks Funds
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
sort-array
Advanced tools
Isomorphic, load-anywhere function to sort an array by scalar, deep or computed values in any standard or custom order
The sort-array npm package is a utility for sorting arrays of objects or primitive values. It provides a simple and flexible API to sort arrays based on various criteria, including multiple fields and custom comparator functions.
Sort by Single Field
This feature allows you to sort an array of objects by a single field. In this example, the array of objects is sorted by the 'age' field.
const sortArray = require('sort-array');
const data = [{ name: 'John', age: 30 }, { name: 'Jane', age: 25 }, { name: 'Jim', age: 35 }];
const sortedData = sortArray(data, { by: 'age' });
console.log(sortedData);
Sort by Multiple Fields
This feature allows you to sort an array of objects by multiple fields. In this example, the array is first sorted by 'age' and then by 'name'.
const sortArray = require('sort-array');
const data = [{ name: 'John', age: 30 }, { name: 'Jane', age: 25 }, { name: 'Jim', age: 35 }];
const sortedData = sortArray(data, { by: ['age', 'name'] });
console.log(sortedData);
Sort in Descending Order
This feature allows you to sort an array of objects in descending order. In this example, the array is sorted by the 'age' field in descending order.
const sortArray = require('sort-array');
const data = [{ name: 'John', age: 30 }, { name: 'Jane', age: 25 }, { name: 'Jim', age: 35 }];
const sortedData = sortArray(data, { by: 'age', order: 'desc' });
console.log(sortedData);
Custom Comparator Function
This feature allows you to use a custom comparator function to sort the array. In this example, the array of numbers is sorted in descending order using a custom comparator function.
const sortArray = require('sort-array');
const data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
const sortedData = sortArray(data, { comparator: (a, b) => b - a });
console.log(sortedData);
Lodash is a popular utility library that provides a wide range of functions for manipulating arrays, objects, and other data types. It includes a `_.sortBy` function that can be used to sort arrays of objects by one or more fields. Compared to sort-array, Lodash offers a broader set of utilities beyond just sorting.
Underscore is another utility library similar to Lodash, providing a variety of functions for working with arrays, objects, and other data types. It includes an `_.sortBy` function for sorting arrays of objects. Like Lodash, Underscore offers a comprehensive set of utilities in addition to sorting.
array-sort is a lightweight package specifically designed for sorting arrays of objects. It provides a simple API for sorting by one or more fields. Compared to sort-array, array-sort is more focused on sorting and does not include additional utilities.
Isomorphic, load-anywhere function to sort an array by scalar, deep or computed values in any standard or custom order.
const sortArray = require('sort-array')
Some trivial examples to demonstrate typical usage.
Sort an array of strings in ascending order (the default).
> const partsOfTheDay = ['twilight', 'afternoon', 'morning', 'evening']
> sortArray(partsOfTheDay)
[ 'afternoon', 'evening', 'morning', 'twilight' ]
Sort an array of strings in descending order.
> sortArray(partsOfTheDay, { order: 'desc' })
[ 'twilight', 'morning', 'evening', 'afternoon' ]
The default value for options.order
is 'asc'
. You can also specify 'desc'
or the name of a property from the customOrders
object. For example, sort parts of the day by the order in which they occur.
> sortArray(partsOfTheDay, {
order: 'time',
customOrders: {
time: ['morning', 'afternoon', 'evening', 'twilight']
}
})
[ 'morning', 'afternoon', 'evening', 'twilight' ]
Pass one or more property names to options.by
to sort an array of objects by those properties.
> const repositories = [
{ name: '75lb/sort-array', openIssues: 0, closedIssues: 4 },
{ name: 'lwsjs/local-web-server', openIssues: 4, closedIssues: 80 },
{ name: 'jsdoc2md/jsdoc-api', openIssues: 3, closedIssues: 47 }
]
> sortArray(repositories, {
by: 'openIssues',
order: 'desc'
})
[
{ name: 'lwsjs/local-web-server', openIssues: 4, closedIssues: 80 },
{ name: 'jsdoc2md/jsdoc-api', openIssues: 3, closedIssues: 47 },
{ name: '75lb/sort-array', openIssues: 0, closedIssues: 4 }
]
Sort by a computed field, i.e. a computed value that doesn't exist in the input dataset. Define your computed fields in the options.computed
object, each value being a function which takes an array member as input and returns the primitive value to be sorted by. In this example we sort by total
(the name of the computed field supplied in options.computed
).
> const repositories = [
{ name: '75lb/sort-array', openIssues: 0, closedIssues: 4 },
{ name: 'lwsjs/local-web-server', openIssues: 4, closedIssues: 80 },
{ name: 'jsdoc2md/jsdoc-api', openIssues: 3, closedIssues: 47 }
]
> sortArray(repositories, {
by: 'total',
order: 'desc',
computed: {
total: repository => repository.openIssues + repository.closedIssues
}
})
[
{ name: 'lwsjs/local-web-server', openIssues: 4, closedIssues: 80 },
{ name: 'jsdoc2md/jsdoc-api', openIssues: 3, closedIssues: 47 },
{ name: '75lb/sort-array', openIssues: 0, closedIssues: 4 }
]
You can use computed fields to sort by values deep in an object structure.
> const data = [
{ inner: { number: 2 } },
{ inner: { number: 3 } },
{ inner: { number: 1 } }
]
> sortArray(data, {
by: 'number',
computed: {
number: row => row.inner.number
}
})
[
{ inner: { number: 1 } },
{ inner: { number: 2 } },
{ inner: { number: 3 } }
]
Sort by multiple columns using multiple custom orders.
> const attributes = [
{ skill: 'accuracy', confidence: 'medium' },
{ skill: 'power', confidence: 'high' },
{ skill: 'speed', confidence: 'low' },
{ skill: 'power', confidence: 'low' },
{ skill: 'speed', confidence: 'high' },
{ skill: 'accuracy', confidence: 'low' },
{ skill: 'speed', confidence: 'medium' },
{ skill: 'accuracy', confidence: 'high' },
{ skill: 'power', confidence: 'medium' }
]
> sortArray(attributes, {
by: ['skill', 'confidence'],
order: ['skill', 'confidence'],
customOrders: {
skill: ['accuracy', 'speed', 'power'],
confidence: ['low', 'medium', 'high'],
}
})
[
{ skill: 'accuracy', confidence: 'low' },
{ skill: 'accuracy', confidence: 'medium' },
{ skill: 'accuracy', confidence: 'high' },
{ skill: 'speed', confidence: 'low' },
{ skill: 'speed', confidence: 'medium' },
{ skill: 'speed', confidence: 'high' },
{ skill: 'power', confidence: 'low' },
{ skill: 'power', confidence: 'medium' },
{ skill: 'power', confidence: 'high' }
]
Please visit the sort-array wiki for more examples.
Isomorphic, load-anywhere function to sort an array by scalar, deep or computed values in any standard or custom order.
Example
const sortArray = require('sort-array')
Array
⏏Kind: Exported function
Returns: Array
- Returns the array that was passed in.
Param | Type | Description |
---|---|---|
array | Array | The input array to sort. It is sorted in place. |
[options] | object | Sort options. |
[options.by] | Array.<string> | One or more property names or computed fields to sort by. Specifying property names is only relevant when sorting an array of objects. |
[options.order] | Array.<string> | One or more sort orders. Specify 'asc' , 'desc' or a property name from the options.customOrders object. |
[options.customOrders] | object | A dictionary object containing one or more custom orders. Each custom order value must be an array defining the order expected values must be sorted in. |
[options.computed] | object | A dictionary object containing one or more computed field functions. The function will be invoked once per item in the array. Each invocation will receive the array item as input and must return a primitive value by which the array can be sorted. |
[options.nullRank] | number | Configures whether null values will be sorted before or after defined values. Set to -1 for before, 1 for after. Defaults to 1 . |
[options.undefinedRank] | number | Configures whether undefined values will be sorted before or after defined values. Set to -1 for before, 1 for after. Defaults to 1 . |
This library is compatible with Node.js, the Web and any style of module loader. It can be loaded anywhere, natively without transpilation.
Node.js:
const sortArray = require('sort-array')
Within Node.js with ECMAScript Module support enabled:
import sortArray from 'sort-array'
Within an modern browser ECMAScript Module:
import sortArray from './node_modules/sort-array/dist/index.mjs'
Old browser (adds window.sortArray
):
<script nomodule src="./node_modules/sort-array/dist/index.js"></script>
© 2015-24 Lloyd Brookes <75pound@gmail.com>.
Tested by test-runner. Documented by jsdoc-to-markdown.
FAQs
Isomorphic, load-anywhere function to sort an array by scalar, deep or computed values in any standard or custom order
The npm package sort-array receives a total of 242,485 weekly downloads. As such, sort-array popularity was classified as popular.
We found that sort-array demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.