1. compare-func
Get a compare function for array to sort
compare-func
Package: compare-func
Created by: stevemao
Last modified: Mon, 13 Jun 2022 19:40:34 GMT
Version: 2.0.0
License: MIT
Downloads: 20,727,928
Repository: https://github.com/stevemao/compare-func

Install

npm install compare-func
yarn add compare-func

NPM version Build Status Dependency Status Coverage Status

Get a compare function for array to sort

Install

 $ npm install --save compare-func

Usage

 var compareFunc = require('compare-func');

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

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

// sort by the `x` propery, then `y`
[{x: 'c', y: 'c'}, {x: 'b', y: 'a'}, {x: 'b', y: 'b'}].sort(compareFunc(['x', 'y']));
//=> [{x: 'b', y: 'a'}, {x: 'b', y: 'b'}, {x: 'c', y: 'c'}]

// sort by the returned value
[{x: 'b'}, {x: 'a'}, {x: 'c'}].sort(compareFunc(function(el) {
  return el.x;
}));
//=> [{x: 'a'}, {x: 'b'}, {x: 'c'}]

API

compareFunc([property])

Returns a compare function for array to sort

property

Type: string, function or array of either

If missing it sorts on itself.

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

  • sort-on - Sort an array on an object property

License

MIT © Steve Mao

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