1.0.0 • Published 10 years ago
objectsort v1.0.0
ObjectSort
Easy way to sort an array of objects by key.
Install
You can install ObjectSort using NPM:
npm install objectsortUsage
ObjectSort(array, columns, order);Where:
array: array that you want to sort.columns: an array or string with thearraykeys that you want to sort.order: an array or string with the order. You must useASCfor ascendent order, orDESCfor descendent order.
The method returns a new array sorted with your specifications.
Example of single column sort:
//Import library
var ObjectSort = require('objectsort');
//Create the new array with your objects
var array = [
{ "id": 1, "name": "John" },
{ "id": 2, "name": "Kevin" },
{ "id": 3, "name": "Alexis" },
{ "id": 4, "name": "Tom" }
];
//Sort by name in ascendent order
var sorted = ObjectSort(array, 'name', 'ASC');
/* Will generate:
[ { "id": 2, "name": "Kevin" },
{ "id": 1, "name": "John" },
{ "id": 2, "name": "Kevin" },
{ "id": 4, "name": "Tom" } ]
*/Example of multi-column sort:
//Import library
var ObjectSort = require('objectsort');
//Create the new array with your objects
var 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 = ObjectSort(array, ['points', 'name'], ['DESC', 'ASC']);
/* 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.