GithubHelp home page GithubHelp logo

jherax / array-sort-by Goto Github PK

View Code? Open in Web Editor NEW
39.0 3.0 0.0 260 KB

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

License: ISC License

JavaScript 100.00%
array sort ordering javascript sort-criteria arrange accent desc asc compare umd-modules amd requirejs commonjs objects

array-sort-by's Introduction

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.

array-sort-by's People

Contributors

jherax avatar sebastianpuchet avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

array-sort-by's Issues

babel-plugin-add-module-exports

When using webpack + babel to build my simple app this error message is shown on compile...

ERROR in ./node_modules/array-sort-by/src/sort-by.js
Module build failed: ReferenceError: Unknown plugin "babel-plugin-add-module-exports" specified 
  in "/project/node_modules/array-sort-by/package.json" 
  at 0, attempted to resolve relative to "/project/node_modules/array-sort-by"
    at /project/node_modules/babel-core/lib/transformation/file/options/option-manager.js:180:17
    at Array.map (native)
    at Function.normalisePlugins (/project/node_modules/babel-core/lib/transformation/file/options/option-manager.js:158:20)
    at OptionManager.mergeOptions (/project/node_modules/babel-core/lib/transformation/file/options/option-manager.js:234:36)
    at OptionManager.init (/project/node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
    at File.initOptions (/project/node_modules/babel-core/lib/transformation/file/index.js:212:65)
    at new File (/project/node_modules/babel-core/lib/transformation/file/index.js:135:24)
    at Pipeline.transform (/project/node_modules/babel-core/lib/transformation/pipeline.js:46:16)
    at transpile (/project/node_modules/babel-loader/lib/index.js:50:20)
    at Object.module.exports (/project/node_modules/babel-loader/lib/index.js:175:20)
 @ ./src/App.js
 @ ./src/index.js
 @ multi babel-polyfill ./src/index.js

Should the 'array-sort-by' package.json be including the babel plugin ???

ie

For ie it not work right?

TypeError: Cannot assign to read only property '28' of string ' **Bea ~#2005** 18402 moons

Hello!

I was trying to use your module to sort in descending order my leaderboard in quick.db, but I couldn't. It gives me this error:
gtrkhyrkth

Why?

Here is my leaderboard code:
`const Discord = require("discord.js");
const db = require('quick.db');
var sortBy = require('array-sort-by');
var currencyFormatter = require('currency-formatter'); //For currency
var fs = require('fs'); //FileSystem

exports.run = async (bot, message, args) => {
const resp = await db.startsWith('moons', { sort: '.data'});
resp.length = 10;
let finalOutput = ' ';
for (var i in resp) {
var us = bot.users.get(resp[i].ID.split("")[1])
//moons
${us.id}
let Moonsdisplay;
let TotalMoons;
let moons = await db.fetch(moons_${us.id})
if (moons === null) db.set(moons_${us.id}, 0);
else TotalMoons = moons;
if (TotalMoons === undefined) TotalMoons = 0;
let amount = parseInt(args.join(' '));

if (TotalMoons > 1000000) { Moonsdisplay = 'Infinitas' } else {Moonsdisplay = TotalMoons}
var usermoons = Moonsdisplay;
finalOutput += **${bot.users.get(resp[i].ID.split("_")[1]).tag}** + ' ' + usermoons + moons \n; // - Moons: ${resp[i].data}
console.log(finalOutput)
var arr = ['teste', 'do', 'caralho']
var msgtosend = await sortBy(finalOutput, item => 'desc:' + item)
}
message.channel.send({
embed: {
"description": msgtosend,
"title": 'Top de Moons',
"color": 16777215
}
})
}
module.exports.command = {
name: 'topmoons',
aliases: ['leaderboard'],
description: 'Veja os mais ricos do servidor!',
category: "Economia",
usage: 's!topmoons',
enabled: false
}`

Please fix this.

Import Failed in React native

import sortBy from 'array-sort-by'; iam using es2015 syntax to import js files

error: bundling: ReferenceError: Unknown plugin "babel-plugin-add-module-exports" specified in "/Users/jagadeesh/Projects/working/xxx/Presentation/yyyy/node_modules/array-sort-by/package.json" at 0, attempted to resolve relative to "/Users/jagadeesh/Projects/working/xxx/Presentation/yyyy/node_modules/array-sort-by"
    at /Users/jagadeesh/Projects/working/xxx/Presentation/yyyy/node_modules/babel-core/lib/transformation/file/options/option-manager.js:180:17
    at Array.map (native)
    at Function.normalisePlugins (/Users/jagadeesh/Projects/working/xxx/Presentation/yyyy/node_modules/babel-core/lib/transformation/file/options/option-manager.js:158:20)
    at OptionManager.mergeOptions (/Users/jagadeesh/Projects/working/xxxx/Presentation/yyyy/node_modules/babel-core/lib/transformation/file/options/option-manager.js:234:36)
    at OptionManager.init (/Users/jagadeesh/Projects/working/xxxx/Presentation/yyyy/node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
    at File.initOptions (/Users/jagadeesh/Projects/working/xxx/Presentation/yyyy/node_modules/babel-core/lib/transformation/file/index.js:212:65)
    at new File (/Users/jagadeesh/Projects/working/xxxx/Presentation/yyyy/node_modules/babel-core/lib/transformation/file/index.js:135:24)
    at Pipeline.transform (/Users/jagadeesh/Projects/working/xxx/Presentation/yyyy/node_modules/babel-core/lib/transformation/pipeline.js:46:16)
    at Object.transform (/Users/jagadeesh/Projects/working/iCommandV3/Presentation/yyyy/node_modules/react-native/packager/transformer.js:109:25)

Cannot find module 'array-sort-by' from '...'

I have a number of React Jest / Enzyme tests which test a component that uses array-sort-by

i include the following (naming my default import as arraySort)

// make sorting by types and nested object easier
import arraySort from 'array-sort-by';

and when i have version 1.1.0 installed everything works as expected and the test all pass. However when I upgrade to version 1.2.0 then the test fail to run with the error message above....

The code still compiles but fails to run with a
(0 , _arraySortBy.sortBy) is not a function

What do I need to import in order to get version 1.2.0 importing / running - as before ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.