node package manager
Love JavaScript? Your insights can make it even better. Take the 2017 JavaScript Ecosystem Survey »

3

3

Performs a multi-level three-way comparison on numbers/strings and returns 1, 0, or -1.

Primarily useful in complex sort() callbacks.

Installation

npm install 3 --save

Usage

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), Stephen, John (#1)