Created
June 12, 2019 13:50
-
-
Save ar2zee/4d65a038e58e45dd3eb60e4d5dc442b4 to your computer and use it in GitHub Desktop.
Sorting an array of Object
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 purchases = [ | |
{ name: 'Popcorn', price: 5.75 }, | |
{ name: 'Movie Ticket', price: 12 }, | |
{ name: 'Soda', price: 3.75 }, | |
{ name: 'Candy', price: 5 }, | |
]; | |
const sortByMapped = (map,compareFn) => (a,b) => compareFn(map(a),map(b)); | |
const byValue = (a,b) => a - b; | |
const toPrice = e => e.price; | |
const byPrice = sortByMapped(toPrice,byValue); | |
console.log([...purchases].sort(byPrice)); | |
/* | |
[ | |
{ name: "Soda", price: 3.75 }, | |
{ name: "Candy", price: 5 }, | |
{ name: "Popcorn", price: 5.75 }, | |
{ name: "Movie Ticket", price: 12 } | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment