var data = [
{id:4, name:"Josema", age:34, work: {isworking:true} },
{id:5, name:"Enzo", age:29, work: {isworking:true} },
{id:2, name:"Josema", age:29, work: {isworking:false} },
{id:1, name:"Enzo", age:29, work: {isworking:false} },
{id:3, name:"Enzo", age:34, work: {isworking:false} }
];
data.sortBy('name', 'age');
console.log( data );
/*
[ { id: 5, name: 'Enzo', age: 29, work: { isworking: true } },
{ id: 1, name: 'Enzo', age: 29, work: { isworking: false } },
{ id: 3, name: 'Enzo', age: 34, work: { isworking: false } },
{ id: 2, name: 'Josema', age: 29, work: { isworking: false } },
{ id: 4, name: 'Josema', age: 34, work: { isworking: true } } ]
*/
console.log( sortBy(data, 'name', 'age') );
/*
[ { id: 5, name: 'Enzo', age: 29, work: { isworking: true } },
{ id: 1, name: 'Enzo', age: 29, work: { isworking: false } },
{ id: 3, name: 'Enzo', age: 34, work: { isworking: false } },
{ id: 2, name: 'Josema', age: 29, work: { isworking: false } },
{ id: 4, name: 'Josema', age: 34, work: { isworking: true } } ]
*/
You can remove Array.prototype.sortBy
for the prototype definition if you do not want overwrite the Array object.
console.log( sortBy(data.slice(0), '-name') ); // I use slice here because I want to create a new array instead of change the order of the original
/*
[ { id: 4, name: 'Josema', age: 34, work: { isworking: true } },
{ id: 2, name: 'Josema', age: 29, work: { isworking: false } },
{ id: 5, name: 'Enzo', age: 29, work: { isworking: true } },
{ id: 1, name: 'Enzo', age: 29, work: { isworking: false } },
{ id: 3, name: 'Enzo', age: 34, work: { isworking: false } } ]
*/
Just adding a dash before the property.
console.log( sortBy(data, 'work.isworking') );
/*
[ { id: 2, name: 'Josema', age: 29, work: { isworking: false } },
{ id: 1, name: 'Enzo', age: 29, work: { isworking: false } },
{ id: 3, name: 'Enzo', age: 34, work: { isworking: false } },
{ id: 4, name: 'Josema', age: 34, work: { isworking: true } },
{ id: 5, name: 'Enzo', age: 29, work: { isworking: true } } ]
*/
Works as deep as you want.