Giter VIP home page Giter VIP logo

sort-array's Introduction

view on npm npm module downloads Gihub repo dependents Gihub package dependents Node.js CI js-standard-style

sort-array

Isomorphic, load-anywhere function to sort an array by scalar, deep or computed values in any standard or custom order.

const sortArray = require('sort-array')

Synopsis

Some trivial examples to demonstrate typical usage.

Sorting an array of primitives

Ascending order

Sort an array of strings in ascending order (the default).

> const partsOfTheDay = ['twilight', 'afternoon', 'morning', 'evening']

> sortArray(partsOfTheDay)
[ 'afternoon', 'evening', 'morning', 'twilight' ]

Descending order

Sort an array of strings in descending order.

> sortArray(partsOfTheDay, { order: 'desc' })
[ 'twilight', 'morning', 'evening', 'afternoon' ]

Custom sort order

The default value for options.order is 'asc'. You can also specify 'desc' or the name of a property from the customOrders object. For example, sort parts of the day by the order in which they occur.

> sortArray(partsOfTheDay, {
  order: 'time',
  customOrders: {
    time: ['morning', 'afternoon', 'evening', 'twilight']
  }
})
[ 'morning', 'afternoon', 'evening', 'twilight' ]

Sorting an array of objects

Sort by object property

Pass one or more property names to options.by to sort an array of objects by those properties.

> const repositories = [
  { name: '75lb/sort-array', openIssues: 0, closedIssues: 4 },
  { name: 'lwsjs/local-web-server', openIssues: 4, closedIssues: 80 },
  { name: 'jsdoc2md/jsdoc-api', openIssues: 3, closedIssues: 47 }
]

> sortArray(repositories, {
  by: 'openIssues',
  order: 'desc'
})
[
  { name: 'lwsjs/local-web-server', openIssues: 4, closedIssues: 80 },
  { name: 'jsdoc2md/jsdoc-api', openIssues: 3, closedIssues: 47 },
  { name: '75lb/sort-array', openIssues: 0, closedIssues: 4 }
]

Sort by computed field

Sort by a computed field, i.e. a computed value that doesn't exist in the input dataset. Define your computed fields in the options.computed object, each value being a function which takes an array member as input and returns the primitive value to be sorted by. In this example we sort by total (the name of the computed field supplied in options.computed).

> const repositories = [
  { name: '75lb/sort-array', openIssues: 0, closedIssues: 4 },
  { name: 'lwsjs/local-web-server', openIssues: 4, closedIssues: 80 },
  { name: 'jsdoc2md/jsdoc-api', openIssues: 3, closedIssues: 47 }
]

> sortArray(repositories, {
  by: 'total',
  order: 'desc',
  computed: {
    total: repository => repository.openIssues + repository.closedIssues
  }
})
[
  { name: 'lwsjs/local-web-server', openIssues: 4, closedIssues: 80 },
  { name: 'jsdoc2md/jsdoc-api', openIssues: 3, closedIssues: 47 },
  { name: '75lb/sort-array', openIssues: 0, closedIssues: 4 }
]

Sort by deep object values

You can use computed fields to sort by values deep in an object structure.

> const data = [
  { inner: { number: 2 } },
  { inner: { number: 3 } },
  { inner: { number: 1 } }
]

> sortArray(data, {
  by: 'number',
  computed: {
    number: row => row.inner.number
  }
})
[
  { inner: { number: 1 } },
  { inner: { number: 2 } },
  { inner: { number: 3 } }
]

Sort by multiple fields

Sort by multiple columns using multiple custom orders.

> const attributes = [
  { skill: 'accuracy', confidence: 'medium' },
  { skill: 'power', confidence: 'high' },
  { skill: 'speed', confidence: 'low' },
  { skill: 'power', confidence: 'low' },
  { skill: 'speed', confidence: 'high' },
  { skill: 'accuracy', confidence: 'low' },
  { skill: 'speed', confidence: 'medium' },
  { skill: 'accuracy', confidence: 'high' },
  { skill: 'power', confidence: 'medium' }
]

> sortArray(attributes, {
  by: ['skill', 'confidence'],
  order: ['skill', 'confidence'],
  customOrders: {
    skill: ['accuracy', 'speed', 'power'],
    confidence: ['low', 'medium', 'high'],
  }
})
[
  { skill: 'accuracy', confidence: 'low' },
  { skill: 'accuracy', confidence: 'medium' },
  { skill: 'accuracy', confidence: 'high' },
  { skill: 'speed', confidence: 'low' },
  { skill: 'speed', confidence: 'medium' },
  { skill: 'speed', confidence: 'high' },
  { skill: 'power', confidence: 'low' },
  { skill: 'power', confidence: 'medium' },
  { skill: 'power', confidence: 'high' }
]

Please visit the sort-array wiki for more examples.

API Reference

sort-array

Isomorphic, load-anywhere function to sort an array by scalar, deep or computed values in any standard or custom order.

Example

const sortArray = require('sort-array')

sortArray(array, [options]) ⇒ Array

Kind: Exported function
Returns: Array - Returns the array that was passed in.

Param Type Description
array Array The input array to sort. It is sorted in place.
[options] object Sort options.
[options.by] Array.<string> One or more property names or computed fields to sort by. Specifying property names is only relevant when sorting an array of objects.
[options.order] Array.<string> One or more sort orders. Specify 'asc', 'desc' or a property name from the options.customOrders object.
[options.customOrders] object A dictionary object containing one or more custom orders. Each custom order value must be an array defining the order expected values must be sorted in.
[options.computed] object A dictionary object containing one or more computed field functions. The function will be invoked once per item in the array. Each invocation will receive the array item as input and must return a primitive value by which the array can be sorted.
[options.nullRank] number Configures whether null values will be sorted before or after defined values. Set to -1 for before, 1 for after. Defaults to 1.
[options.undefinedRank] number Configures whether undefined values will be sorted before or after defined values. Set to -1 for before, 1 for after. Defaults to 1.

Load anywhere

This library is compatible with Node.js, the Web and any style of module loader. It can be loaded anywhere, natively without transpilation.

Node.js:

const sortArray = require('sort-array')

Within Node.js with ECMAScript Module support enabled:

import sortArray from 'sort-array'

Within an modern browser ECMAScript Module:

import sortArray from './node_modules/sort-array/dist/index.mjs'

Old browser (adds window.sortArray):

<script nomodule src="./node_modules/sort-array/dist/index.js"></script>

© 2015-22 Lloyd Brookes <[email protected]>.

Isomorphic test suite by test-runner and web-runner. Documented by jsdoc-to-markdown.

sort-array's People

Contributors

75lb avatar markreeder 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

Watchers

 avatar  avatar  avatar

sort-array's Issues

Suggestion

I needed to sort a list by string ex: all items with the property "source"
if it equals to "Unlinked" it should drop to the end of the list
if it doesn't equals to "Unlinked" it should be shifted to start of the array
I managed to do this like this:

  return sortArray(list, {
    by: "source",
    order,
    computed: {
      total: source => (source === "Unlinked" ? 1 : 0),
    },
  });  

I suggest you add a support for that

reverse sorting?

Hi -- is there any way to control whether the sorting for a property is in ascending or descending order?

How are NULL values handled?

I'm using sortArray with an array that contains null values in field.

sortArray(myArray, {by: ['fieldA',fieldB']})

fieldA contains two values, null and the number "1". Regardless of how I sort the array (asc or desc), the null values are always at the end. I was expecting them to be first when using asc order but they are last in both cases.

Does it work if the key has dot character ?

So I have a JSON in the format

{"homepage_card.title":{"type":"StructuredText","value":[{"type":"heading1","text":"Test Card","spans":[]}]},"homepage_card.type":{"type":"Select","value":"default"},"homepage_card.sequence":{"type":"Number","value":4},"homepage_card.description":{"type":"StructuredText","value":[{"type":"paragraph","text":"This is some description","spans":[]}]},"homepage_card.background_image":{"type":"Image","value":{"main":{"dimensions":{"width":960,"height":800},"alt":null,"copyright":null,"url":"https://wroomdev.s3.amazonaws.com/tutoblanktemplate%2F97109f41-140e-4dc9-a2c8-96fb10f14051_star.gif"},"views":{}}},"homepage_card.label":{"type":"Text","value":"Label"},"homepage_card.rotating_cards":{"type":"Group","value":[{}]}}

where the keys have a dot.

It did not seem to work for this case when I was trying to sort homepage_card.sequence.value

Add ability to sort by a computed property value

For example

const fixture = [
  { a: 5, b: 10 },
  { a: 2, b: 10 },
  { a: 3, b: 10 },
  { a: 1, b: 10 },
  { a: 4, b: 10 }
]
const by = [
  item => item.a + item.b
]
/* Sorts recordset by the result of `a + b` for each object in the array */
const result = sort(fixture, by)

Add input validation

Low priority but would be nice to have some input validation which ensures the config supplied is valid. E.g. ensure a customOrder is either a function or array of values. The following is invalid and should raise an "invalid config" exception:

sortArray(arr, {
  by: 'something',
  order: 'broken',
  customOrders: {
    broken: new Date()
  }
})

Bugfix

Sorting of this failed:

   var ar = [[99, "a"], [1, "a"]];
   sortArray(ar, {by:[1,0]});

I changed this line
if (result === 0 && by[byIndex + 1]) {
to this
if (result === 0 && (undefined !== by[byIndex + 1])) {
to fix it.

add the ability to sort in a new array

Just found out about this library, great job!
reading the code, the sort happens in-place. It would be nice if I could leave the original array as is, and get a new sorted array

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.