README
Array sortBy
Sorts an array and allows specify multiple sorting criteria. It has support for accented characters, and ignores case sensitive to sort strings correctly.
Content
Getting started
To include this library into your package manager with npm
or yarn
# with npm
$ npm install array-sort-by
# with yarn
$ yarn add array-sort-by
The sortBy
function has the following signature:
/**
* @param {Array} array: the list of elements to sort
* @param {Function} parser: (optional) transforms each item and specifies the sorting mode
* @return {Array}
*/
sortBy(array: Array, parser: Function) : Array
sortBy(array: Array) : Array
The optional parameter parser
is a function that transforms each element
being iterated and sets the sorting rules: ascending or descending.
Here you can specify the way of sorting by multiple fields.
The parser
callback has the following signature:
/**
* @param {Any} item: the element being iterated over the list
* @param {Number} index: the index of the element in the list
* @return {Any}
*/
parser(item: Any, index: Number) : Any
parser(item: Any) : Any
Also, a new static method mapAccents
has been added to the sortBy
function.
This method allows to register a map of accents in order to sort strings correctly.
Signature:
/**
* @param {String} accents: the string with the accents
* @param {String} replacements: the replacement for each accent
*/
sortBy.mapAccents(accents: String, replacements: String) : void
Problem solved: when you try order an array of non ASCII characters like this
['é', 'a', 'ú', 'c']
, you will obtain a strange result['c', 'e', 'á', 'ú']
. That happens because.sort()
does not work correctly with accented characters.
By default mapAccents
has an internal mapping with accents and their replacements:
"ÂâÀàÁáÄäÃãÅåÊêÈèÉéËëÎîÌìÍíÏïÔôÒòÓóÖöÕõÛûÙùÚúÜüÑñÝýÿ"
"AaAaAaAaAaAaEeEeEeEeIiIiIiIiOoOoOoOoOoUuUuUuUuNnYyy"
To register a new set of special characters you must provide their replacements:
// register the special characters
sortBy.mapAccents(
'ª@