npm package for sorting in reactjs
var sortBy = require('sort-by'),
users = [];
users = [{
id: 7,
name: 'Foo',
age: '34',
email: { primary: '[email protected]' }
}, {
id: 3,
name: 'Baz',
age: '67',
email: { primary: '[email protected]' }
}, {
id: 4,
name: 'Bar',
age: '67',
email: { primary: '[email protected]' }
}];
users.sort(sortBy('name', 'age'));
/**
* result:
* [{id: 4, name: 'Bar', age: '67', email: { primary: '[email protected]' }},
* {id: 3, name: 'Baz', age: '67', email: { primary: '[email protected]' }},
* {id: 7, name: 'Foo', age: '34', email: { primary: '[email protected]' }}]
*/
/**
* Use `-` to reverse the sort order
*/
users.sort(sortBy('-id', 'name'));
/*
* result:
* [{id: 7, name: 'Foo', age: '34', email: { primary: '[email protected]' }},
* {id: 4, name: 'Bar', age: '67', email: { primary: '[email protected]' }},
* {id: 3, name: 'Baz', age: '67', email: { primary: '[email protected]' }}]
*/
/**
* Use `.` notation to traverse nested properties. See [object-path](https://www.npmjs.org/package/object-path) npm module for support.
*/
users.sort(sortBy('age', 'email.primary'));
/*
* result:
* [{id: 7, name: 'Foo', age: '34', email: { primary: '[email protected]' }},
* {id: 4, name: 'Bar', age: '67', email: { primary: '[email protected]' }},
* {id: 3, name: 'Baz', age: '67', email: { primary: '[email protected]' }}]
*/