Skip to content

Instantly share code, notes, and snippets.

@C5H8NNaO4
Created June 3, 2020 11:44
Show Gist options
  • Save C5H8NNaO4/15f9b776ce7e4540eacb64b77e3b711d to your computer and use it in GitHub Desktop.
Save C5H8NNaO4/15f9b776ce7e4540eacb64b77e3b711d to your computer and use it in GitHub Desktop.
Sort by fields
You can write a simple helper function that accepts an array of fields to sort by. The logic is simple: Iterate over the fields and return -1 if a is less then b or 1 if a is greater then b. If they are equal, do the same comparison for the next field. If all comparisons are equal, return 0.
const data = [
{id:1,created:"2020:12:12T10:12:56",start:"2020:12:10"},
{id:1,created:"2020:12:12T10:12:58",start:"2020:12:09"},
{id:1,created:"2020:12:12T10:12:57",start:"2020:12:08"},
{id:1,created:"2020:12:12T10:12:53",start:"2020:12:11"},
{id:1,created:"2020:12:12T10:12:53",start:"2020:12:09"},
{id:1,created:"2020:12:12T10:12:53",start:"2020:12:10"},
]
function sortByFields (arr, fields) {
return arr.sort ((a, b) => {
for (const field of fields) {
if (a[field] < b[field]) return -1;
if (a[field] > b[field]) return 1;
}
return 0
})
}
const srt = sortByFields(data, ['created', 'start']);
console.log (srt)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment