Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Powerful mechanism to sort arrays or array of objects by one or more properties. You can also specify a custom comparer function.

License

NotificationsYou must be signed in to change notification settings

jherax/array-sort-by

Repository files navigation

Powerful mechanism to sort arrays or array of objects by one or more properties.You can also specify a custom comparer function.

By default it has support for some accented characters(seemapAccents).

Content

  1. Getting started
  2. Including the library
  3. Examples

Getting started

To include this library into your package manager withnpm oryarn

# with npm$ npm install array-sort-by# with yarn$ yarn add array-sort-by

ThesortBy function has the following signature:

/** *@param  {Array} array: the list of elements to sort *@param  {Function} parser: transforms each item and specifies the sorting mode *@return {Array} */sortBy(array:Array) :ArraysortBy(array:Array,parser:Function) :Array

If the parameterparser is not provided, then the array is sorted usingthe default implementation ofArray.prototype.sort().

Otherwise, the parameterparser is a function that transforms each elementbeing iterated and sets the sorting rules:ascending ordescending.Here you can specify the way of sorting by multiple properties.

Theparser 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) :Anyparser(item:Any) :Any

See examples in the sectionExamples

mapAccents

A new static methodmapAccents has been added to thesortBy function.This method allows to register a map of accented characters in order tosort the string accordingly.

Signature:

/** *@param {String} accents: a string with accented characters *@param {String} replacements: a string with the replacement for each accent */sortBy.mapAccents(accents:String,replacements:String) :void

Problem solved: when you try to order strings with non ASCII characterslike this:['é', 'a', 'ú', 'c'], you will obtain strange results after sortingthe array:['c', 'e', 'á', 'ú']. That happens because by default the methodArray.prototype.sort() does not work correctly with accented characters.

But the static methodmapAccents comes to the rescue, because it has aninternal mapping with some accented characters and their replacements:

// accents"ÂâÀàÁáÄäÃãÅåÊêÈèÉéËëÎîÌìÍíÏïÔôÒòÓóÖöÕõÛûÙùÚúÜüÑñÝýÿ","AaAaAaAaAaAaEeEeEeEeIiIiIiIiOoOoOoOoOoUuUuUuUuNnYyy"// replacements

You also may extend the accented characters and register a new set of specialcharacters with their respective replacements:

// register special characterssortBy.mapAccents('ª@$','aas',);constarr=['$impson','Cªl@bazä','M@ría','Cal@bªzA'];sortBy(arr);/** * expected: * ["Cªl@bazä", "Cal@bªzA", "M@ría", "$impson"] * * translated as: * ["CALABAZA", "CALABAZA", "MARIA", "SIMPSON"] */sortBy(arr,item=>`DESC:${item}`);/** * expected: * ["$impson", "M@ría", "Cal@bªzA", "Cªl@bazä"] * * translated as: * ["SIMPSON", "MARIA", "CALABAZA", "CALABAZA"] */

In the example above, after callingsortBy.mapAccents() we extendedthe internal mapping, by adding the new accents and their replacementsat the beginning of the mapping, honoring the user mapping first:

// accents: added "ª@$""ª@$ÂâÀàÁáÄäÃãÅåÊêÈèÉéËëÎîÌìÍíÏïÔôÒòÓóÖöÕõÛûÙùÚúÜüÑñÝýÿ""aasAaAaAaAaAaAaEeEeEeEeIiIiIiIiOoOoOoOoOoUuUuUuUuNnYyy"// replacements

☗ Back to Index

Including the library

array-sort-by can be included directly from a CDN in your site:

<!-- from unpkg.com --><scriptsrc="https://unpkg.com/array-sort-by/dist/sort-by.min.js"></script><!-- from unpkg.com, including polyfills --><scriptsrc="https://unpkg.com/array-sort-by/dist/sort-by-full.min.js"></script><!-- from rawgit.com --><scriptsrc="https://cdn.rawgit.com/jherax/array-sort-by/1.2.1/dist/sort-by.min.js"></script><!-- from rawgit.com, including polyfills --><scriptsrc="https://cdn.rawgit.com/jherax/array-sort-by/1.2.1/dist/sort-by-full.min.js"></script>

In the above case, the functionsortBy is included asglobal object in the browser.

AssortBy is built asUMD(Universal Module Definition), it canbe included from module loaders such asCommonJS,ES2015 ImportsorAMD RequireJS.

CommonJS

varsortBy=require('array-sort-by');

ES2015 Imports

importsortByfrom'array-sort-by';

AMD

// using RequireJSrequirejs.config({paths:{// remove the extension .js'array-sort-by':'<PATH>/sort-by.min'}});require(['array-sort-by'],function(sortBy){sortBy(someArray);});

See an example with RequireJS here:http://jsfiddle.net/FdKTn/75/

☗ Back to Index

Examples

Default sorting (ASC)

letarr=[10,8,5,3,0,7,4,5,1];sortBy(arr);/** * expected: * [0, 1, 3, 4, 5, 5, 7, 8, 10] */

Sorting DESC: numbers

letarr=[5,1,8,0,3,7,10,4,3,8];sortBy(arr,n=>-n);/** * expected: * [10, 8, 8, 7, 5, 4, 3, 3, 1, 0] */

Sorting DESC: date-strings as Date

letarr=['1983/03/06','1980/12/24','1985/08/31','1983/03/05'];sortBy(arr,(s)=>-newDate(s));/** * expected: * ["1985/08/31", "1983/03/06", "1983/03/05", "1980/12/24"] */

Sorting DESC: strings

Because we use the minus(-) symbol to specify a descending order,it would produce aNaN value if used with aString value.So the flag"desc:" (not case sensitive) is prefixedto the string value in theparser callback.

vararr=['único','cosas','Árbol','fútbol','algo'];sortBy(arr,item=>'desc:'+item);/** * expected: * ["único", "fútbol", "cosas", "Árbol", "algo"] */// sorting ASC: accented wordssortBy(arr);/** * expected: * ["algo", "Árbol", "cosas", "fútbol", "único"] */

Sorting ASC: accented words by @text

vararr=[{id:10,text:'Woche'},{id:20,text:'wöchentlich'},{id:30,text:'wäre'}];sortBy(arr,item=>item.text);/** * expected: * [ *   { id: 30, text: "wäre" }, *   { id: 10, text: "Woche" }, *   { id: 20, text: "wöchentlich" } * ] */

Sorting DESC by @id, after ASC by @dob (as Date)

letarr=[{id:8,dob:'1985/08/31'},{id:2,dob:'1980/12/24'},{id:5,dob:'1983/03/06'},{id:8,dob:'1983/03/06'}];sortBy(arr,(o)=>[-o.id,newDate(o.dob)]);/** * expected: * [ *   { id: 8, dob: "1983/03/06" }, *   { id: 8, dob: "1985/08/31" }, *   { id: 5, dob: "1983/03/06" }, *   { id: 2, dob: "1980/12/24" } * ] */

Sorting DESC by @name

letarr=[{id:4,name:'Pedro'},{id:6,name:'Lucía'},{id:7,name:'paco'},{id:3,name:'luis'}];sortBy(arr,item=>`DESC:${item.name}`);/** * expected: * [ *   { id: 4, name: "Pedro" }, *   { id: 7, name: "paco" }, *   { id: 3, name: "luis" }, *   { id: 6, name: "Lucía" } * ] */

Sorting ASC by @name, after DESC by @age, after ASC by @id

letarr=[{id:9,age:26,name:'pedro'},{id:6,age:21,name:'Pedro'},{id:7,age:26,name:'Maria'},{id:2,age:26,name:'maría'}];sortBy(arr,item=>[item.name,-item.age,item.id]);/** * expected: * [ *   { id: 2, age: 26, name: "maría" }, *   { id: 7, age: 26, name: "Maria" }, *   { id: 9, age: 26, name: "pedro" }, *   { id: 6, age: 21, name: "Pedro" } * ] */

☗ Back to Index

Versioning

This projects adopts theSemantic Versioning(SemVer) guidelines:

<MAJOR>.<MINOR>.<PATCH>

Given a version number MAJOR.MINOR.PATCH, increment the:

  1. MAJOR version when you make incompatible API changes.
  2. MINOR version when you add functionality in a backwards-compatible manner.
  3. PATCH version when you make backwards-compatible bug fixes.

Issues

To report an issue and keep traceability of bug-fixes, please report to:

License

This project has been released under theISC license.This license applies ONLY to the source of this repository and does not extend to any other distribution,or any other 3rd party libraries used in a repository. SeeLICENSE file for more information.

About

Powerful mechanism to sort arrays or array of objects by one or more properties. You can also specify a custom comparer function.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors2

  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp