Skip to content

Instantly share code, notes, and snippets.

@ToniMaunde
Last active June 19, 2023 07:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ToniMaunde/4d85017d4a1f0b00e7838e8c31ab3d26 to your computer and use it in GitHub Desktop.
Save ToniMaunde/4d85017d4a1f0b00e7838e8c31ab3d26 to your computer and use it in GitHub Desktop.
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