als-smart-sort

1.0.0 • Public • Published

als-smart-sort

A versatile sorting function for JavaScript arrays, als-smart-sort provides the capability to sort arrays based on various data types, including nested properties. This function is designed to handle arrays of objects with ease, sorting by numeric, string, or date properties, while also dealing with nested object properties.

Installation

npm install als-smart-sort

Function Parameters

  • array (Array): The array to be sorted.
  • propPath (String): The path to the property used for sorting. Nested properties can be accessed with dot notation (e.g., prop.subprop).
  • asc (Boolean): Optional. Determines the sorting order. Set to true for ascending order (default) or false for descending order.

Note: The function performs type validation and returns an empty array if the input is invalid.

Browser support

<script src="node_modules/als-smart-sort/sort.js"></script>

Usage

Here are some examples of how als-smart-sort can be used:

Basic Sorting

const smartSort = require('als-smart-sort');

// Sorting an array of objects by a numeric property
const numericArray = [{ value: 3 }, { value: 1 }, { value: 2 }];
console.log(smartSort(numericArray, 'value')); // [{ value: 1 }, { value: 2 }, { value: 3 }]

// Sorting by a string property in descending order
const stringArray = [{ name: 'Bob' }, { name: 'Alice' }, { name: 'Charlie' }];
console.log(smartSort(stringArray, 'name', false)); // [{ name: 'Charlie' }, { name: 'Bob' }, { name: 'Alice' }]

Sorting with Nested Properties

// Sorting an array of objects with nested properties
const nestedArray = [{ data: { score: 10 } }, { data: { score: 5 } }, { data: { score: 7 } }];
console.log(smartSort(nestedArray, 'data.score')); // [{ data: { score: 5 } }, { data: { score: 7 } }, { data: { score: 10 } }]

Sorting Mixed Number and String Representations

// Sorting an array with mixed number and string representations
const mixedArray = [{ value: '10' }, { value: 5 }, { value: '2' }];
console.log(smartSort(mixedArray, 'value')); // [{ value: '2' }, { value: 5 }, { value: '10' }]

Sorting by date

const array = [
   { event: 'C', date: new Date('2022-01-03') },
   { event: 'A', date: new Date('2022-01-01') },
   { event: 'B', date: new Date('2022-01-02') }
];
const sorted = smartSort(array, 'date');
console.log(sorted)

Output:

[
  { event: 'A', date: 2022-01-01T00:00:00.000Z },
  { event: 'B', date: 2022-01-02T00:00:00.000Z },
  { event: 'C', date: 2022-01-03T00:00:00.000Z }
]

Package Sidebar

Install

npm i als-smart-sort

Weekly Downloads

9

Version

1.0.0

License

MIT

Unpacked Size

12.2 kB

Total Files

4

Last publish

Collaborators

  • alexsorkin