https://github.com/lamansky/3
[Node.js] Performs a multi-level three-way comparison on numbers/strings and returns 1, 0, or -1.
https://github.com/lamansky/3
compare comparison javascript nodejs nodejs-modules sort three-way
Last synced: 2 months ago
JSON representation
[Node.js] Performs a multi-level three-way comparison on numbers/strings and returns 1, 0, or -1.
- Host: GitHub
- URL: https://github.com/lamansky/3
- Owner: lamansky
- License: mit
- Created: 2017-12-09T15:01:05.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2018-02-03T13:44:53.000Z (over 8 years ago)
- Last Synced: 2025-10-10T17:06:55.320Z (9 months ago)
- Topics: compare, comparison, javascript, nodejs, nodejs-modules, sort, three-way
- Language: JavaScript
- Homepage:
- Size: 4.88 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
- License: license.txt
Awesome Lists containing this project
README
# 3
Performs a multi-level three-way comparison on numbers/strings and returns 1, 0, or -1.
Primarily useful in complex [`sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) callbacks.
## Installation
```bash
npm install 3 --save
```
## Usage
```javascript
const compare3Way = require('3')
const people = [
{name: 'John', age: 27},
{name: 'Stephen', age: 26},
{name: 'John', age: 25},
]
// Sort by name
people.sort((a, b) => compare3Way(a.name, b.name)) // John, John, Stephen
// Sort by age
people.sort((a, b) => compare3Way(a.age, b.age)) // John, Stephen, John
// Multi-level sort: First by name, then by age
people.sort((a, b) => compare3Way(a.name, b.name, a.age, b.age)) // John (#2), John (#1), Stephen
// Normally empty strings are sorted so they come first,
// but you can use the `emptyStringsLast` option to change that.
compare3Way('', 'str') // -1
compare3Way('', 'str', {emptyStringsLast: true}) // 1
```