ObjectSort
Easy way to sort an array of objects by key.
Install
You can install ObjectSort using NPM:
npm install objectsort
Usage
ObjectSort(array, columns, order);
Where:
array
: array that you want to sort.columns
: an array or string with thearray
keys that you want to sort.order
: an array or string with the order. You must useASC
for ascendent order, orDESC
for descendent order.
The method returns a new array sorted with your specifications.
Example of single column sort:
//Import libraryvar ObjectSort = ; //Create the new array with your objectsvar array = "id": 1 "name": "John" "id": 2 "name": "Kevin" "id": 3 "name": "Alexis" "id": 4 "name": "Tom" ; //Sort by name in ascendent ordervar sorted = ; /* Will generate:[ { "id": 2, "name": "Kevin" }, { "id": 1, "name": "John" }, { "id": 2, "name": "Kevin" }, { "id": 4, "name": "Tom" } ]*/
Example of multi-column sort:
//Import libraryvar ObjectSort = ; //Create the new array with your objectsvar array = "id": 1 "name": "John" "points": 40 "id": 2 "name": "Kevin" "points": 50 "id": 3 "name": "Alexis" "points": 30 "id": 4 "name": "Tom" "points": 40 ; //First sort by points (order DESC) and then by name (order ASC)var sorted = ; /* Will generate:[ { "id": 2, "name": "Kevin", "points": 50 }, { "id": 1, "name": "John", "points": 40 }, { "id": 4, "name": "Tom", "points": 40 }, { "id": 3, "name": "Alexis", "points": 30 } ]*/
License
ObjectSort is under the MIT license.