1. sort-on
Sort an array on an object property
sort-on
Package: sort-on
Created by: sindresorhus
Last modified: Sat, 30 Sep 2023 17:40:43 GMT
Version: 6.0.0
License: MIT
Downloads: 715,093
Repository: https://github.com/sindresorhus/sort-on

Install

npm install sort-on
yarn add sort-on

sort-on

Sort an array on an object property

Install

 npm install sort-on

Usage

 import sortOn from 'sort-on';

// Sort by an object property
sortOn([{x: 'b'}, {x: 'a'}, {x: 'c'}], 'x');
//=> [{x: 'a'}, {x: 'b'}, {x: 'c'}]

// Sort descending by an object property
sortOn([{x: 'b'}, {x: 'a'}, {x: 'c'}], '-x');
//=> [{x: 'c'}, {x: 'b'}, {x: 'a'}]

// Sort by a nested object property
sortOn([{x: {y: 'b'}}, {x: {y: 'a'}}], 'x.y');
//=> [{x: {y: 'a'}}, {x: {y: 'b'}}]

// Sort descending by a nested object property
sortOn([{x: {y: 'b'}}, {x: {y: 'a'}}], '-x.y');
//=> [{x: {y: 'b'}, {x: {y: 'a'}}}]

// Sort by the `x` property, then `y`
sortOn([{x: 'c', y: 'c'}, {x: 'b', y: 'a'}, {x: 'b', y: 'b'}], ['x', 'y']);
//=> [{x: 'b', y: 'a'}, {x: 'b', y: 'b'}, {x: 'c', y: 'c'}]

// Sort by the returned value
sortOn([{x: 'b'}, {x: 'a'}, {x: 'c'}], element => element.x);
//=> [{x: 'a'}, {x: 'b'}, {x: 'c'}]

API

sortOn(array, property, options)

Returns a new sorted version of the given array.

array

Type: unknown[]

The array to sort.

property

Type: string | string[] | Function

The string can be a dot path to a nested object property.

Prefix it with - to sort it in descending order.

options

Type: object

locales

Type: string | string[]
Default: The default locale of the JavaScript runtime.

One or more locales to use when sorting strings.

Should be a locale string or array of locale strings that contain one or more language or locale tags.

If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale.

This parameter must conform to BCP 47 standards. See Intl.Collator for more details.

localeOptions

Type: Intl.CollatorOptions

Comparison options.

Dependencies

RELATED POST

10 Must-Know Windows Shortcuts That Will Save You Time

10 Must-Know Windows Shortcuts That Will Save You Time

Arrays vs Linked Lists: Which is Better for Memory Management in Data Structures?

Arrays vs Linked Lists: Which is Better for Memory Management in Data Structures?

Navigating AWS Networking: Essential Hacks for Smooth Operation

Navigating AWS Networking: Essential Hacks for Smooth Operation

Achieving Stunning Visuals with Unity's Global Illumination

Achieving Stunning Visuals with Unity's Global Illumination

Nim's Hidden Gems: Lesser-known Features for Writing Efficient Code

Nim's Hidden Gems: Lesser-known Features for Writing Efficient Code