Created
October 21, 2021 05:15
-
-
Save Alonso-Pablo/8d52b5658d8c690343f15b8c77d2b4ac to your computer and use it in GitHub Desktop.
Sort an object[] by keys
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
function sortBy(array, keys) { | |
let i = 0 | |
return [...array].sort((a,b) => compareBy(a, b, keys, i)) | |
} | |
function compareBy(a, b, keys, i) { | |
if (a[keys[i]] > b[keys[i]]) return 1 | |
if (a[keys[i]] < b[keys[i]]) return -1 | |
i++ | |
if (!keys[i]) return 0 | |
return compareBy(a, b, keys, i) | |
} | |
const arr = [ | |
{id:1, documentos: 2}, | |
{id:1, documentos: 1}, | |
{id:1, documentos: 7}, | |
{id:2, documentos: 3}, | |
{id:2, documentos: 0}, | |
{id:3, documentos: 2}, | |
] | |
const keys = [ | |
'id', | |
'documentos', | |
] | |
sortBy(arr, keys) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment