Sort an array of objects by any property value, at any depth, in any custom order
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
jsdoc2md
lib
test
.gitignore
.travis.yml
LICENSE
README.md
package-lock.json
package.json

README.md

view on npm npm module downloads Build Status Dependency Status js-standard-style

sort-array

Sort an array of objects by any property value, at any depth, in any custom order.

Example

const sortBy = require('sort-array')

sortBy(recordset, columnNames, [customOrder]) ⇒ Array

Kind: Exported function

Param Type Description
recordset Array.<object> Input array of objects
columnNames string | Array.<string> One or more property expressions to sort by, e.g. 'name' or 'name.first'.
[customOrder] object Custom sort order definitions. An object where each key is the property expression and the value is an array specifying the sort order. Example:
{ importance: [ 'speed', 'strength', 'intelligence' ]}

Example
with this data

> DJs = [
  { name: 'Trevor', slot: 'twilight' },
  { name: 'Chris', slot: 'twilight' },
  { name: 'Mike', slot: 'afternoon' },
  { name: 'Rodney', slot: 'morning' },
  { name: 'Chris', slot: 'morning' },
  { name: 'Zane', slot: 'evening' }
]

sort by slot using the default sort order (alphabetical)

> sortBy(DJs, 'slot')
[ { name: 'Mike', slot: 'afternoon' },
  { name: 'Zane', slot: 'evening' },
  { name: 'Chris', slot: 'morning' },
  { name: 'Rodney', slot: 'morning' },
  { name: 'Chris', slot: 'twilight' },
  { name: 'Trevor', slot: 'twilight' } ]

specify a custom sort order for slot

> const slotOrder = [ 'morning', 'afternoon', 'evening', 'twilight' ]
> sortBy(DJs, 'slot', { slot: slotOrder })
[ { name: 'Rodney', slot: 'morning' },
  { name: 'Chris', slot: 'morning' },
  { name: 'Mike', slot: 'afternoon' },
  { name: 'Zane', slot: 'evening' },
  { name: 'Trevor', slot: 'twilight' },
  { name: 'Chris', slot: 'twilight' } ]

sort by slot then name

> sortBy(DJs, ['slot', 'name'], { slot: slotOrder })
[ { name: 'Chris', slot: 'morning' },
  { name: 'Rodney', slot: 'morning' },
  { name: 'Mike', slot: 'afternoon' },
  { name: 'Zane', slot: 'evening' },
  { name: 'Chris', slot: 'twilight' },
  { name: 'Trevor', slot: 'twilight' } ]

sort by nested property values (at any depth) using dot notation (e.g. 'inner.number')

> input = [
  { inner: { number: 5 } },
  { inner: { number: 2 } },
  { inner: { number: 3 } },
  { inner: { number: 1 } },
  { inner: { number: 4 } }
]

> sortBy(input, 'inner.number')
[ { inner: { number: 1 } },
  { inner: { number: 2 } },
  { inner: { number: 3 } },
  { inner: { number: 4 } },
  { inner: { number: 5 } } ]

a custom order for a nested property looks like this:

const customOrder = {
  'inner.number': [ 1, 2, 4, 3, 5 ]
}

© 2015-17 Lloyd Brookes <75pound@gmail.com>. Documented by jsdoc-to-markdown.