Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 1,000,000+ packages pre-installed, including comparators with all npm packages installed. Try it out:

var comparators = require("comparators")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

comparators v3.0.2

Provides chainable comparator-function generators a la Java 8 Comparators


Build Status

Java8-style chainable comparators for Javascript

Raison d'être

In working with JS, I've run across situations where I need multi-key sorting in my Backbone collections -- which can sort themselves using the same type of comparator function as Array.prototype.sort expects.

When Java 8 rolled out, it brought with it a Comparator interface, that allowed chaining comparators for multi-attribute sort like this:


I really liked that approach, so I brought that into Javascript with the same(ish) syntax. That's this library.

Usage and examples

Directly translating our above Java 8 code, we could do the following:

/* Demo data */
var people = [
  {lastName: "Baggins", firstName: "Frodo"},
  {lastName: "Gamgee",  firstName: "Samwise"},
  {lastName: "Baggins", firstName: "Bilbo"}

sortedPeople = people.sort(Comparators.comparing("lastName").thenComparing("firstName"));

/* sortedPeople is now:
  {lastName: "Baggins", firstName: "Bilbo"},
  {lastName: "Baggins", firstName: "Frodo"},
  {lastName: "Gamgee",  firstName: "Samwise"},

For more examples, see the tests in test/comparators.spec.js.

Where and how can I use it?

It works in the browser without a module system, as a CommonJS module, and as an AMD module.

The simplest (but global-namespace-polluting) way to use it is to include comparators.js in a script tag:

<script type="text/javascript" src="comparators.min.js"></script>

In node/CommonJS loaders, just require it (it's available on NPM as comparators):

var Comparators = require("comparators").default; // the .default is necessary because of how Typescript compiles to commonjs

It works similarly in AMD loaders (require.js used in the below example):

require(['comparators.min'], function(Comparators){
  /* Do a thing! */


Comparators.js is made available under the MIT License (Quick summary of it here)


RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free