Created
August 8, 2020 19:45
-
-
Save naxty/8f0bca295077aaa74f03b88d104a6df9 to your computer and use it in GitHub Desktop.
Sort array of objects alphabetically in TypeScript
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
type Category = { | |
name: string | |
} | |
const categories:Array<Category> = [ | |
{ | |
name: "Travel" | |
}, | |
{ | |
name: "Electronics" | |
} | |
]; | |
const sort = (array: Array<Category>) => { | |
return array.sort((a: Category, b: Category) => { | |
if (a.name < b.name){ | |
return -1; | |
} | |
if (a.name > b.name){ | |
return 1; | |
} | |
return 0; | |
}) | |
} | |
console.log(sort(categories)) | |
// [ { "name": "Electronics" }, { "name": "Travel" } ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment