Last active
October 4, 2021 19:59
-
-
Save enlacee/a964baa6009e2297186a91791f4ffdf6 to your computer and use it in GitHub Desktop.
order object or array with .sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
** 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