Skip to content

Instantly share code, notes, and snippets.

@Alonso-Pablo
Created October 21, 2021 05:15
Show Gist options
  • Save Alonso-Pablo/8d52b5658d8c690343f15b8c77d2b4ac to your computer and use it in GitHub Desktop.
Save Alonso-Pablo/8d52b5658d8c690343f15b8c77d2b4ac to your computer and use it in GitHub Desktop.
Sort an object[] by keys
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