Skip to content

apurvapatel141092/sort-json-array

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

sort-json-array NPM version

Sort an array of JSON objects by a property

NPM

Install

Install with npm:

$ npm install sort-json-array --save

Usage

Sort an array of JSON objects by a property:

var sortJsonArray = require('sort-json-array');

sortJsonArray([{name: 'c'}, {name: 'a'}, {name: 'b'}], 'name');
//=> [{name: 'a'}, {name: 'b'}, {name: 'c'}]

sortJsonArray([{name: 'c'}, {name: 'a'}, {name: 'b'}], 'name','des');
//=> [{name: 'c'}, {name: 'b'}, {name: 'a'}]

sortJsonArray([{name: 'c'}, {name: 'a'}, {name: 'b'}], 'name','asc');
//=> [{name: 'a'}, {name: 'b'}, {name: 'c'}]

Params

sortJsonArray(array, property, order);
  • array: {Array} The array to be sorted.
  • property: {String}: The Property based on what the array should be sorted.
  • order: {String}: Pass 'des' if you want array to be sorted in descending order. Pass 'asc' if you want array to be sorted in ascending order. By default it will be sorted in ascending order.

Examples

var sortJsonArray = require('sort-json-array');

var user = [
  { name: 'c', location: "San Jose" },
  { name: 'a', location: "San Francisco"},
  { name: 'b', location: "New York" },
];

// sort by `name` in ascending order because order is not passed
console.log(sortJsonArray(user, 'name'));

// sort by `location` in descending order
console.log(sortJsonArray(user, 'location','des'));

// sort by `name` in ascending order
console.log(sortJsonArray(user, 'name','asc'));

Running tests

Install dev dependencies and run test:

$ npm install -d && npm test

Author

Apurva Patel

License

Copyright © 2016, Apurva Patel. Released under the MIT license.


About

Sort an array of JSON objects by a property - npm package

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published