Skip to content

Instantly share code, notes, and snippets.

@ar2zee
Created June 12, 2019 13:50
Show Gist options
  • Save ar2zee/4d65a038e58e45dd3eb60e4d5dc442b4 to your computer and use it in GitHub Desktop.
Save ar2zee/4d65a038e58e45dd3eb60e4d5dc442b4 to your computer and use it in GitHub Desktop.
Sorting an array of Object
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