https://github.com/tiaanduplessis/prop-sort
Sort array of objects based on property (supports nested properties)
https://github.com/tiaanduplessis/prop-sort
array nested object property sorting
Last synced: 6 months ago
JSON representation
Sort array of objects based on property (supports nested properties)
- Host: GitHub
- URL: https://github.com/tiaanduplessis/prop-sort
- Owner: tiaanduplessis
- License: mit
- Created: 2017-04-29T18:32:27.000Z (almost 9 years ago)
- Default Branch: master
- Last Pushed: 2019-06-02T22:44:02.000Z (over 6 years ago)
- Last Synced: 2025-07-27T21:45:52.809Z (7 months ago)
- Topics: array, nested, object, property, sorting
- Language: JavaScript
- Size: 29.3 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
prop-sort
Sort array of objects based on property (supports nested properties)
Table of Contents
Table of Contents
## Install
```sh
$ npm install --save prop-sort
# OR
$ yarn add prop-sort
```
## Usage
The original array **is not mutated**.
```js
const propSort = require('prop-sort')
const data = [
{
value: 1,
priority: 'c'
},
{
value: 2,
priority: 'a'
},
{
value: 9
},
{
value: 1,
priority: 'z'
},
{
value: 2,
priority: 'a'
}
]
console.log(propSort(data, 'priority'))
//[ { value: 9 },
// { value: 2, priority: 'a' },
// { value: 2, priority: 'a' },
// { value: 1, priority: 'c' },
// { value: 1, priority: 'z' } ]
```
Use `dot notation` to sort by nested properties:
```js
const propSort = require('prop-sort')
const data = [
{
value: 1,
foo: {
bar: 8
}
},
{
value: 2,
foo: {
bar: 1
}
},
{
value: 9,
foo: {
bar: 5
}
},
{
value: 1,
foo: {
bar: 99
}
},
{
value: 2,
foo: {
bar: 70
}
}
]
console.log(propSort(data, 'foo.bar'))
// [ { value: 2, foo: { bar: 1 } },
// { value: 9, foo: { bar: 5 } },
// { value: 1, foo: { bar: 8 } },
// { value: 2, foo: { bar: 70 } },
// { value: 1, foo: { bar: 99 } } ]
```
Can also use own custom comparator function:
```js
const propSort = require('prop-sort')
data = [...]
propSort(data, 'property', (valueOfFirstProperty, valueOfSecondProperty) => {
//...
})
```
## Contribute
Contributions are welcome. Please open up an issue or create PR if you would like to help out.
Note: If editing the README, please conform to the [standard-readme](https://github.com/RichardLitt/standard-readme) specification.
## License
Licensed under the MIT License.