npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

array-sort-compare

v1.0.1

Published

Generic compare function for Array.prototype.sort()

Downloads

36

Readme

array-sort-compare

Generic type-aware compare function for Array.prototype.sort() and sortDeep.

Build Status Build status for master NPM Badge

JavaScript arrays are sorted using string comparison by default, because that's what the spec say. This is an issue when sorting an array which has mixed types.

Before

> const arr = [["a", 10, 1], ["a", 2, 1]]
> arr.sort()

[ [ 'a', 10, 1 ], [ 'a', 2, 1 ] ]  // 10 is before 2, and 2nd-level arrays are not sorted

After

> const { sortDeep, compare } = require('array-sort-compare')
> const arr = [["a", 10, 2], ["a", 2, 1]]
> sortDeep(arr, compare())

[ [ 1, 2, 'a' ], [ 2, 10, 'a' ] ]

You can also use just the compareFunction provided by this module. This doesn't sort nested arrays though:

> const { compare } = require('array-sort-compare')
> const arr = [["a", 10], ["a", 2]]
> arr.sort(compare())

[ [ 'a', 2 ], [ 'a', 10 ] ]

The tests contain good examples of how it works. Warning: no performance tests have been ran against the module.

Other usage examples

Descending order

const { sortDeep, compare } = require('array-sort-compare')
const arr = [["a", 10, 2], ["a", 2, 1]]
sortDeep(arr, compare('desc'))

Changing the order between types

const { sortDeep, compare } = require('array-sort-compare')
const arr = [["a", 10, 2], ["a", 2, 1]]
sortDeep(arr, compare({
  // Sort booleans first as an example
  typeOrder: ['boolean', 'number', 'string', 'array', 'object', 'null', 'undefined']
}))

Extending types

const isPlainObject = require('lodash.isplainobject')
const { sortDeep, compare } = require('array-sort-compare')

const arr = [["a", 10, 2], ["a", 2, 1]]
sortDeep(arr, compare({
  // Our new category of objects (type) is called 'weekday'
  // It's an object looking like this:
  // { day: 'MONDAY', value: 0 }
  typeOrder: ['weekday', 'number', 'string', 'boolean', 'array', 'object', 'null', 'undefined']
  typeCheckers: {
    // the 'weekday' key needs to match the string in typeOrder
    weekday: obj => isPlainObject(obj) && obj.hasOwnProperty('day') && obj.hasOwnProperty('value')
  },
  typeComparers: {
    // the 'weekday' key needs to match the string in typeOrder
    weekday: (a, b) => a.value - b.value
  }
}))

API

sortDeep(array, [compareFunction])

Sorts given array in-place. Similar to Array.prototype.sort(), but also recursively sorting nested arrays inside the array.

Recommended way to use .sortDeep() is together with the .compare() function:

const { sortDeep, compare } = require('array-sort-compare')
const arr = [["a", 10, 2], ["a", 2, 1]]
sortDeep(arr, compare())

Would result to [[1, 2, 'a'], [2, 10, 'a' ]].

compareFunction

Specifies a function that defines the sort order. If omitted, the array is sorted by default Array.prototype.sort() behavior. The default sorting is done according to each character's Unicode code point value, according to the string conversion of each element. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort.

compare([opts])

Returns a comparator Function which can be passed to Array.sort().

opts

Can be either a string describing the sorting direction or a configuration object. Default: "asc".

Valid string values:

  • asc Sort in ascending order
  • desc Sort in descending order

The default object configuration. Useful for advanced use cases such as specifying a custom order between types or even adding new types.

{
  // Sorting direction. Valid values are 'asc' and 'desc'.
  // Note: this doesn't affect the order of different types defined in `opts.typeOrder`
  direction: 'asc',

  // These type names is a categorization of this module. The names can be anything, as long
  // as counterparts are found from `opts.typeCheckers` and `opts.typeComparers`.
  typeOrder: ['number', 'string', 'boolean', 'array', 'object', 'null', 'undefined'],

  // Functions which detect given types. The function receives an object of unknown type as the
  // first parameter and returns true if it matches the type. For example
  // { number: obj => typeof obj === 'number' }
  //
  // Note: the given object is *merged* to the default opts.typeCheckers
  typeCheckers: {
    number: _.isNumber,
    string: _.isString,
    boolean: _.isBoolean,
    array: _.isArray,
    object: _.isPlainObject,
    null: _.isNull,
    undefined: _.isUndefined,
  },

  // Compare functions for each type. For default cases the signature is the same as
  // Array.prototype.sort(), see
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description
  // In addition to that, the compare function receives a third positional argument `genericCompare`,
  // which can be used for sorting nested structures such as arrays (recursion).
  // See test/test-all.js for an advanced. example
  //
  // Simple example:
  // { number: (a, b) => a - b }
  //
  // Note: the given object is *merged* to the default opts.typeComparers
  typeComparers: {
    number: numberCompare,
    string: stringCompare,
    boolean: numberCompare,
    array: arrayCompare,
    // object, null and undefined are all using default comparison which considers
    // everything equal. For example two nulls are considered equal
  },

  // Always use 'asc' for these type. Required for recursively sorted "container" types
  ignoreDirectionOfTypes: ['array']
}

Install

npm install array-sort-compare

Resources

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
  • What the spec says about the default compare function: http://www.ecma-international.org/ecma-262/6.0/#sec-sortcompare
  • https://stackoverflow.com/questions/47334234/how-to-implement-array-prototype-sort-default-compare-function

License

MIT