A versatile sorting function for JavaScript arrays, handling various data types and nested properties.
npm install als-smart-sortals-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.
bash
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
`html
`
Usage
Here are some examples of how als-smart-sort can be used:
$3
`javascript
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' }]
`
$3
`javascript
// 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 } }]
`
$3
`javascript
// 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' }]
`
$3
`js
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:
`bash
[
{ 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 }
]
``