Last active
June 19, 2023 07:57
-
-
Save ToniMaunde/4d85017d4a1f0b00e7838e8c31ab3d26 to your computer and use it in GitHub Desktop.
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
const users = [ | |
{ | |
id: 0, | |
status: "inactive", | |
username: "hobbit" | |
}, | |
{ | |
id: 1, | |
status: "active", | |
username: "hobbit 2" | |
}, | |
{ | |
id: 2, | |
status: "inactive", | |
username: "lord of the rings" | |
}, | |
{ | |
id: 3, | |
status: "active", | |
username: "star trek" | |
} | |
]; | |
// add a check to see if .toSorted() is supported | |
function sortBy(collection, attribute, order = "asc") { | |
const collectionCopy = [...collection]; | |
if (order === "asc") { | |
return collectionCopy.toSorted((a, b) => { | |
if (a[attribute] < b[attribute]) return -1; | |
if (a[attribute] > b[attribute]) return 1; | |
return 0; | |
}) | |
} | |
return collectionCopy.toSorted((a, b) => { | |
if (a[attribute] < b[attribute]) return 1; | |
if (a[attribute] > b[attribute]) return -1; | |
return 0; | |
}); | |
} | |
const sortedUsers = sortBy(users, "status"); | |
console.log(sortedUsers); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment