Skip to content

Instantly share code, notes, and snippets.

@enlacee
Last active October 4, 2021 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enlacee/a964baa6009e2297186a91791f4ffdf6 to your computer and use it in GitHub Desktop.
Save enlacee/a964baa6009e2297186a91791f4ffdf6 to your computer and use it in GitHub Desktop.
order object or array with .sort
/**
** Order values custom
** @ref with array = https://stackoverflow.com/questions/1069666/sorting-object-property-by-values
**/
let obj = [{ id: 33, date: 333 }, { id: 11, date: 111 }, { id: 22, date: 222 }, { id: 0, date: 0 }];
var sortable = [];
for (var index in obj) {
sortable.push([obj[index]['id'], obj[index]['date']]);
}
sortable.sort(function(a, b) {
return a[1] - b[1];
});
console.log('sortable', sortable);
/**
* For order DESC only: invert logic
*
* return b[1] - a[1]
**/
/ *************************************************/
// order desc SIMPLE DATA
let items = ['pepe', 'anibal', 'juan', 'max'];
items.sort((a, b) => {
if (a > b)
return -1;
if (a < b)
return 1;
return 0;
});
console.log('items', items);
/ *************************************************/
// order ASC by name (in data object) (complex data)
let THECLIENTS = {};
THECLIENTS.push({id: '65345', name: 'pepe'});
THECLIENTS.push({id: '45433', name: 'anibal'});
// THECLIENTS.sort();
THECLIENTS.sort((a, b) => {
if (a.name > b.name)
return 1;
if (a.name < b.name)
return -1;
return 0;
});
console.log('THECLIENTS', THECLIENTS);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment