2.0.2 • Published 8 years ago

stand-in-order v2.0.2

Weekly downloads
48
License
-
Repository
github
Last release
8 years ago

stand-in-order

Build Status NPM version

Description

  • Sort an array by a primitive type.
  • Sort an array by an object property value.
  • Sort an array by multiple object property values.

Installation

npm install stand-in-order

Using

Available options:

    {
        // true || false - default is true
        ascending: true,

        // 'string' || 'integer' || 'float' || 'boolean' || 'date' - default is 'string'
        type: 'string',       

        // property name to sort by
        name: 'foo',

        // comparator function - defining one will overwrite 'type'        
        compare: null
    }
Primitive Type Example

The sorter takes two arguments. First argument is the array to sort and second is an array of options.

    var sorter = require('stand-in-order');
    sorter(
        ['a', 'b', 'aa', 'bc'],
        [
            {type: 'string', ascending: true, name: null}
        ]
    );
Object Example
    var sorter = require('stand-in-order');
    var list = [
        {
            foo: 1,
            bar: 'z'
        },
        {
            foo: 2,
            bar: 'a'
        },
        {
            foo: 1,
            bar: 'g'
        },
        {
            foo: 1,
            bar: 'c'
        }
    ];
    sorter(list, [
        {name: 'foo', type: 'integer', ascending: true},
        {name: 'bar', type: 'string', ascending: false}
    ]);
Defining Custom Sort
    var compare = function (left, right, ascending) {

        var value = 0;
        if (left === 'open' && (right === 'active' || right === 'close')) {
            value = -1;
        }

        if (left === 'active' && right === 'close') {
            value = -1;
        }

        if (left === 'active' && right === 'open') {
            value = 1;
        }

        if (left === 'close' && (right === 'open' || right === 'active')) {
            value = 1;
        }

        if (left === right) {
            value = 0;
        }

        if (!ascending) {
            if (value === -1 || value === 1) {
                value = value * -1;
            }
        }

        return value;
    };

    var list = ['open', 'close', 'active', 'close', 'active', 'open'];
    sort(list, [
        {compare: compare}
    ]);
    console.log(list);
    // [ 'open', 'open', 'active', 'active', 'close', 'close' ]
2.0.2

8 years ago

2.0.1

8 years ago

1.0.9

10 years ago

1.0.8

10 years ago

1.0.7

10 years ago

0.0.7

10 years ago

0.0.6

10 years ago

0.0.5

10 years ago

0.0.4

10 years ago

0.0.3

10 years ago

0.0.2

10 years ago

0.0.1

10 years ago