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.
npm install als-smart-sort
-
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 totrue
for ascending order (default) orfalse
for descending order.
Note: The function performs type validation and returns an empty array if the input is invalid.
<script src="node_modules/als-smart-sort/sort.js"></script>
Here are some examples of how als-smart-sort
can be used:
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 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 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' }]
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 }
]