Coder Social home page Coder Social logo

jonschlinkert / array-sort Goto Github PK

View Code? Open in Web Editor NEW
74.0 4.0 24.0 28 KB

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.

License: MIT License

JavaScript 100.00%
array sort nodejs javascript compare jonschlinkert

array-sort's Introduction

array-sort NPM version NPM monthly downloads NPM total downloads Linux Build Status Windows Build Status

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.

Install

Install with npm:

$ npm install --save array-sort

Install with yarn:

$ yarn add array-sort

Usage

Sort an array by the given object property:

var arraySort = require('array-sort');

arraySort([{foo: 'y'}, {foo: 'z'}, {foo: 'x'}], 'foo');
//=> [{foo: 'x'}, {foo: 'y'}, {foo: 'z'}]

Reverse order

arraySort([{foo: 'y'}, {foo: 'z'}, {foo: 'x'}], 'foo', {reverse: true});
//=> [{foo: 'z'}, {foo: 'y'}, {foo: 'x'}]

Params

arraySort(array, comparisonArgs);
  • array: {Array} The array to sort
  • comparisonArgs: {Function|String|Array}: One or more functions or object paths to use for sorting.

Examples

Sort blog posts

var arraySort = require('array-sort');

var posts = [
  { path: 'c.md', locals: { date: '2014-01-09' } },
  { path: 'a.md', locals: { date: '2014-01-02' } },
  { path: 'b.md', locals: { date: '2013-05-06' } },
];

// sort by `locals.date`
console.log(arraySort(posts, 'locals.date'));

// sort by `path`
console.log(arraySort(posts, 'path'));

Sort by multiple properties

var arraySort = require('array-sort');

var posts = [
  { locals: { foo: 'bbb', date: '2013-05-06' }},
  { locals: { foo: 'aaa', date: '2012-01-02' }},
  { locals: { foo: 'ccc', date: '2014-01-02' }},
  { locals: { foo: 'ccc', date: '2015-01-02' }},
  { locals: { foo: 'bbb', date: '2014-06-01' }},
  { locals: { foo: 'aaa', date: '2014-02-02' }},
];

// sort by `locals.foo`, then `locals.date`
var result = arraySort(posts, ['locals.foo', 'locals.date']);

console.log(result);
// [ { locals: { foo: 'aaa', date: '2012-01-02' } },
//   { locals: { foo: 'aaa', date: '2014-02-02' } },
//   { locals: { foo: 'bbb', date: '2013-05-06' } },
//   { locals: { foo: 'bbb', date: '2014-06-01' } },
//   { locals: { foo: 'ccc', date: '2014-01-02' } },
//   { locals: { foo: 'ccc', date: '2015-01-02' } } ]

Custom function

If custom functions are supplied, array elements are sorted according to the return value of the compare function. See the docs for Array.sort() for more details.

var arr = [
  {one: 'w', two: 'b'},
  {one: 'z', two: 'a'},
  {one: 'x', two: 'c'},
  {one: 'y', two: 'd'},
];

function compare(prop) {
  return function (a, b) {
    return a[prop].localeCompare(b[prop]);
  };
}

var result = arraySort(arr, function (a, b) {
  return a.two.localeCompare(b.two);
});

console.log(result);
// [ { one: 'z', two: 'a' },
//   { one: 'w', two: 'b' },
//   { one: 'x', two: 'c' },
//   { one: 'y', two: 'd' } ]

Multiple custom functions

var arr = [
  {foo: 'w', bar: 'y', baz: 'w'},
  {foo: 'x', bar: 'y', baz: 'w'},
  {foo: 'x', bar: 'y', baz: 'z'},
  {foo: 'x', bar: 'x', baz: 'w'},
];

// reusable compare function
function compare(prop) {
  return function (a, b) {
    return a[prop].localeCompare(b[prop]);
  };
}

// the `compare` functions can be a list or array
var result = arraySort(arr, compare('foo'), compare('bar'), compare('baz'));

console.log(result);
// [ { foo: 'w', bar: 'y', baz: 'w' },
//   { foo: 'x', bar: 'x', baz: 'w' },
//   { foo: 'x', bar: 'y', baz: 'w' },
//   { foo: 'x', bar: 'y', baz: 'z' } ]

About

Related projects

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.

Contributors

Commits Contributor
10 jonschlinkert
4 doowb
1 iamstolis
1 wkevina

Building docs

(This project's readme.md is generated by verb, please don't edit the readme directly. Any changes to the readme must be made in the .verb.md readme template.)

To generate the readme, run the following command:

$ npm install -g verbose/verb#dev verb-generate-readme && verb

Running tests

Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:

$ npm install && npm test

Author

Jon Schlinkert

License

Copyright © 2017, Jon Schlinkert. Released under the MIT License.


This file was generated by verb-generate-readme, v0.6.0, on September 11, 2017.

array-sort's People

Contributors

doowb avatar iamstolis avatar jonschlinkert avatar mesqueeb avatar wkevina 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  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  avatar

array-sort's Issues

v1.0.0

Hey @doowb, any reason this isn't 1.0? I'm considering using it to replace lodash.sortby

Stable?

Surprisingly it's not mentioned anywhere if this is a stable / deterministic sort. And also which algorithm is used, like timsort?

Question: how to sort on both asc / desc

Dear creator:

I'd want to use your plugin like so:

    var result = arraySort(posts,
                             ['locals.foo', 'locals.date'], 
                             [{reverse: true}, {reverse: false}]
                          );

I'm sure this can be done with custom sorting, but it would be great if you could make this syntax work.

Or even better syntax imo:

    var result = arraySort(posts, [
        {field: 'locals.foo', direction: 'desc'},
        {field: 'locals.date', direction: 'asc'},
    ]);

No compatible call signatures

Using array-sort in typescript for around 16 months, but am now faced wit:

Cannot invoke an expression whose type lacks a call signature. Type '{}' has no compatible call signatures.ts(2349)

Everytime I try use it, even when using the readme files. Has TS update caused this?

Syntax suggestion

I thought of a super clean syntax for your great NPM library @jonschlinkert .

Usage

  • In case of single attribute sort: sort asc with string and desc with -+string
  • In case of multiple attribute sort: add the attributes in an array with the same asc/desc functionality as above

Examples

Single attribute reverse (desc) sort:

let arr = [{foo: 'y'}, {foo: 'z'}, {foo: 'x'}]

arraySort(arr, '-foo')
// Will sort on attribute `foo` as `desc`

Multiple attribute asc & desc sort:

let arr = [{foo: 'y', bar: 'a'}, {foo: 'z', bar: 'b'}, {foo: 'x', bar: 'c'}, {foo: 'x', bar: 'a'}]

arraySort(arr, ['foo', '-bar'])
// Will sort on attribute `foo` as `asc`
//      will sort next on `bar` as `desc`

After sorting, empty strings are at the beginning of the sorted array

const test = [
  { title: 'b' },
  { title: '' },
  { title: 'a' }
]

console.log(arraySort(test, 'title'))

Output:

[
  { title: '' },
  { title: 'a' },
  { title: 'b' }
]

Expected output:

[
  { title: 'a' },
  { title: 'b' },
  { title: '' }
]

Since it's sorting by string, I'd expect empty strings to be last in the array, similar to null values.

Two Number fields not working

Hi

When I use this command it only sorts by uCreated.

arraySort(articles, ["uCreated", "counts.view"], { reverse: true });

It ignores counts.view
If i use either on their own it works fine

Danie

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.