prop-sort

1.0.0 • Public • Published

Table of Contents

Sort array of objects based on property (supports nested properties)



Built with ❤︎ by Tiaan and contributors

Table of Contents

Table of Contents
  • Install
  • Usage
  • Contribute
  • License
  • Install

    $ npm install --save prop-sort
    # OR 
    $ yarn add prop-sort

    Usage

    The original array is not mutated.

    const propSort = require('prop-sort')
     
    const data = [
      {
        value: 1,
        priority: 'c'
      },
      {
        value: 2,
        priority: 'a'
      },
      {
        value: 9
      },
      {
        value: 1,
        priority: 'z'
      },
      {
        value: 2,
        priority: 'a'
      }
    ]
     
    console.log(propSort(data, 'priority'))
    //[ { value: 9 },
    //  { value: 2, priority: 'a' },
    //  { value: 2, priority: 'a' },
    //  { value: 1, priority: 'c' },
    //  { value: 1, priority: 'z' } ]
     

    Use dot notation to sort by nested properties:

    const propSort = require('prop-sort')
     
    const data = [
      {
        value: 1,
        foo: {
          bar: 8
        }
      },
      {
        value: 2,
        foo: {
          bar: 1
        }
      },
      {
        value: 9,
        foo: {
          bar: 5
        }
      },
      {
        value: 1,
        foo: {
          bar: 99
        }
      },
      {
        value: 2,
        foo: {
          bar: 70
        }
      }
    ]
     
    console.log(propSort(data, 'foo.bar'))
    // [ { value: 2, foo: { bar: 1 } },
    //  { value: 9, foo: { bar: 5 } },
    //  { value: 1, foo: { bar: 8 } },
    //  { value: 2, foo: { bar: 70 } },
    //  { value: 1, foo: { bar: 99 } } ]

    Can also use own custom comparator function:

    const propSort = require('prop-sort')
     
    data = [...]
     
    propSort(data, 'property', (valueOfFirstProperty, valueOfSecondProperty) => {
        //...
    })
     

    Contribute

    Contributions are welcome. Please open up an issue or create PR if you would like to help out.

    Note: If editing the README, please conform to the standard-readme specification.

    License

    Licensed under the MIT License.

    Package Sidebar

    Install

    npm i prop-sort

    Weekly Downloads

    1

    Version

    1.0.0

    License

    MIT

    Last publish

    Collaborators

    • tiaanduplessis