All Projects → jherax → array-sort-by

jherax / array-sort-by

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

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to array-sort-by

Requirejs Demo
《RequreJS学习笔记》
Stars: ✭ 164 (+343.24%)
Mutual labels:  commonjs, amd, requirejs
Require Vuejs
RequireJS plugin to async and dynamic load and parse .vue components
Stars: ✭ 143 (+286.49%)
Mutual labels:  amd, requirejs
Angular Async Loader
Load modules and components asynchronously for angular 1.x application.
Stars: ✭ 137 (+270.27%)
Mutual labels:  amd, requirejs
Steal
Gets JavaScript
Stars: ✭ 1,353 (+3556.76%)
Mutual labels:  commonjs, amd
vscode-requirejs
Provides goto definition functionality for require js modules.
Stars: ✭ 20 (-45.95%)
Mutual labels:  amd, requirejs
Pyopencl
OpenCL integration for Python, plus shiny features
Stars: ✭ 790 (+2035.14%)
Mutual labels:  amd, array
Madge
Create graphs from your CommonJS, AMD or ES6 module dependencies
Stars: ✭ 5,635 (+15129.73%)
Mutual labels:  commonjs, amd
invokable
Objects are functions! Treat any Object or Class as a Proc (like Enumerable but for Procs).
Stars: ✭ 40 (+8.11%)
Mutual labels:  array, objects
Webpack
A bundler for javascript and friends. Packs many modules into a few bundled assets. Code Splitting allows for loading parts of the application on demand. Through "loaders", modules can be CommonJs, AMD, ES6 modules, CSS, Images, JSON, Coffeescript, LESS, ... and your custom stuff.
Stars: ✭ 60,034 (+162154.05%)
Mutual labels:  commonjs, amd
TypeScript-AMD-Boilerplate
A TypeScript AMD Grunt Boilerplate with RequireJS
Stars: ✭ 46 (+24.32%)
Mutual labels:  amd, requirejs
Data-Structure-Algorithm-Programs
This Repo consists of Data structures and Algorithms
Stars: ✭ 464 (+1154.05%)
Mutual labels:  array, sort
Faltu
Search sort, filter, limit an array of objects in Mongo-style.
Stars: ✭ 112 (+202.7%)
Mutual labels:  array, sort
Array Sort
Fast and powerful array sorting. Sort an array of objects by one or more properties. Any number of nested properties or custom comparison functions may be used.
Stars: ✭ 58 (+56.76%)
Mutual labels:  array, sort
Conditioner
💆🏻 Frizz free, context-aware, JavaScript modules
Stars: ✭ 1,053 (+2745.95%)
Mutual labels:  amd, requirejs
Leetcode
Provide all my solutions and explanations in Chinese for all the Leetcode coding problems.
Stars: ✭ 5,619 (+15086.49%)
Mutual labels:  array, sort
Node Dependency Tree
Get the dependency tree of a module
Stars: ✭ 383 (+935.14%)
Mutual labels:  commonjs, amd
Image-Sort
Sorts your image at high speed
Stars: ✭ 15 (-59.46%)
Mutual labels:  sort, ordering
array-diff-multidimensional
Compare the difference between two multidimensional arrays in PHP
Stars: ✭ 60 (+62.16%)
Mutual labels:  array, compare
arr-sort
🎉 多重条件下的数组排序方法
Stars: ✭ 20 (-45.95%)
Mutual labels:  array, sort
js-deep-sort-object
Simple module to sort objects recursively by its keys
Stars: ✭ 19 (-48.65%)
Mutual labels:  array, sort

Array sortBy

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 (see mapAccents).

Content

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

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: transforms each item and specifies the sorting mode
 * @return {Array}
 */
sortBy(array: Array) : Array
sortBy(array: Array, parser: Function) : Array

If the parameter parser is not provided, then the array is sorted using the default implementation of Array.prototype.sort().

Otherwise, the 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 properties.

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

See examples in the section Examples

mapAccents

A new static method mapAccents has been added to the sortBy function. This method allows to register a map of accented characters in order to sort 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 characters like this: ['é', 'a', 'ú', 'c'], you will obtain strange results after sorting the array: ['c', 'e', 'á', 'ú']. That happens because by default the method Array.prototype.sort() does not work correctly with accented characters.

But the static method mapAccents comes to the rescue, because it has an internal mapping with some accented characters and their replacements:

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

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

// register special characters
sortBy.mapAccents(
  'ª@$',
  'aas',
);

const arr = ['$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 calling sortBy.mapAccents() we extended the internal mapping, by adding the new accents and their replacements at 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 -->
<script src="https://unpkg.com/array-sort-by/dist/sort-by.min.js"></script>
<!-- from unpkg.com, including polyfills -->
<script src="https://unpkg.com/array-sort-by/dist/sort-by-full.min.js"></script>

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

In the above case, the function sortBy is included as global object in the browser.

As sortBy is built as UMD (Universal Module Definition), it can be included from module loaders such as CommonJS, ES2015 Imports or AMD RequireJS.

CommonJS

var sortBy = require('array-sort-by');

ES2015 Imports

import sortBy from 'array-sort-by';

AMD

// using RequireJS
requirejs.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)

let arr = [10, 8, 5, 3, 0, 7, 4, 5, 1];
sortBy(arr);

/**
 * expected:
 * [0, 1, 3, 4, 5, 5, 7, 8, 10]
 */

Sorting DESC: numbers

let arr = [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

let arr = ['1983/03/06', '1980/12/24', '1985/08/31', '1983/03/05'];
sortBy(arr, (s) => -new Date(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 a NaN value if used with a String value. So the flag "desc:" (not case sensitive) is prefixed to the string value in the parser callback.

var arr = ['único', 'cosas', 'Árbol', 'fútbol', 'algo'];

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

// sorting ASC: accented words
sortBy(arr);
/**
 * expected:
 * ["algo", "Árbol", "cosas", "fútbol", "único"]
 */

Sorting ASC: accented words by @text

var arr = [
  { 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)

let arr = [
  { 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, new Date(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

let arr = [
  { 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

let arr = [
  { 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 the Semantic 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 the ISC 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. See LICENSE file for more information.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].