JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 353777
  • Score
    100M100P100Q166226F
  • License MIT

Sort an array on an object property

Package Exports

  • sort-on

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (sort-on) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

sort-on Build Status

Sort an array on an object property

Install

$ npm install sort-on

Usage

const sortOn = require('sort-on');

// Sort by an object property
sortOn([{x: 'b'}, {x: 'a'}, {x: 'c'}], 'x');
//=> [{x: 'a'}, {x: 'b'}, {x: 'c'}]

// Sort descending by an object property
sortOn([{x: 'b'}, {x: 'a'}, {x: 'c'}], '-x');
//=> [{x: 'c'}, {x: 'b'}, {x: 'a'}]

// Sort by a nested object property
sortOn([{x: {y: 'b'}}, {x: {y: 'a'}}], 'x.y');
//=> [{x: {y: 'a'}}, {x: {y: 'b'}}]

// Sort descending by a nested object property
sortOn([{x: {y: 'b'}}, {x: {y: 'a'}}], '-x.y');
//=> [{x: {y: 'b'}, {x: {y: 'a'}}}]

// Sort by the `x` property, then `y`
sortOn([{x: 'c', y: 'c'}, {x: 'b', y: 'a'}, {x: 'b', y: 'b'}], ['x', 'y']);
//=> [{x: 'b', y: 'a'}, {x: 'b', y: 'b'}, {x: 'c', y: 'c'}]

// Sort by the returned value
sortOn([{x: 'b'}, {x: 'a'}, {x: 'c'}], el => el.x);
//=> [{x: 'a'}, {x: 'b'}, {x: 'c'}]

API

sortOn(array, property)

Returns a new sorted version of the given array.

array

Type: unknown[]

The array to sort.

property

Type: string | string[] | Function

The string can be a dot path to a nested object property. Prepend it with - to sort it in descending order.

License

MIT © Sindre Sorhus