Skip to content
Sort numbers in ascending or descending order
JavaScript
Find file
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.
dist
src
.editorconfig
.gitattributes
.gitignore
.jshintrc
.travis.yml
LICENSE
README.md
appveyor.yml
bower.json
cli.js
gulpfile.js
package.json
test.js

README.md

sort-numbers.js

NPM version Bower version Build Status Build status Coverage Status devDependency Status

Sort numbers in ascending or descending order

sortNumbers([0.45, Infinity, -2]); //=> [-2, 0.45, Infinity]
sortNumbers.desc([ 0.45, Infinity, -2]); //=> [Infinity, 0.45, -2]

Installation

Package managers

npm

npm install sort-numbers

Bower

bower install sort-numbers

Duo

var sortNumbers = require('shinnn/sort-numbers.js');

Standalone

Download the script file directly.

API

sortNumbers(numbers)

numbers: Array of Number without NaN
Return: Array of Number

It returns the array numerically sorted in ascending order.

Note that Array.prototype.sort works as lexical sort by default.

var arr = [100, -2, -Infinity];

sortNumbers(arr); //=> [ -Infinity, -2, 100 ]
arr.sort(); //=> [ -2, -Infinity, 100 ]

It returns an empty array when the argument is an empty array.

It throws a TypeError when the array contains non-number values or NaN.

sortNumbers(new Array()); //=> []

sortNumbers([1, '2', 3]); // throw a type error
sortNumbers([NaN]); // throw a type error

sortNumbers.desc(numbers)

numbers: Array of Number without NaN
Return: Array of Number

It returns the array numerically sorted in descending order.

var arr = [0, 1, 2 ,3];

sortNumbers.desc(arr) //=> [3, 2, 1, 0]
sortNumbers(arr) //=> [0, 1, 2, 3]

sortNumbers.asc(numbers)

An alias to sortNumbers.

CLI

You can use this module as a CLI tool by installing it globally.

npm install -g sort-numbers

Usage

Usage: sort-numbers <number0> [<number1> <number2> ...]

Options:
--desc,    -d  Sort numbers in descending order (ascending order by default)
--help,    -h  Print usage information
--version, -v  Print version

Example

sort-numbers -23 7 -Infinity Infinity 

yields:

-Infinity,-23,7,Infinity

License

Copyright (c) 2014 - 2015 Shinnosuke Watanabe

Licensed under the MIT License.

Something went wrong with that request. Please try again.