Last active
June 23, 2017 07:23
-
-
Save chriswrightdesign/31c56ceb5a8b0ba5ca8581c8d480ea43 to your computer and use it in GitHub Desktop.
Flip function
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
// our example array to work with | |
const myArr = [{ | |
name: 'bob', | |
id: 5, | |
}, { | |
name: 'scott', | |
id: 4, | |
}, { | |
name: 'matt', | |
id: 6, | |
}, { | |
name: 'chris', | |
id: 1 | |
}, | |
]; | |
// the Problem: sorting an array ascending is usually a - b, descending is b - a | |
const mySortedArray = myArr.concat().sort((a, b) => a - b)); | |
// for an object we might want to sort by a specific property | |
const anotherSortedArray = myArr.concat().sort((start, end) => start.id - end.id); | |
// lets extract our sorting function, and make it so we can pass in any property to sort by | |
const ascendingProp = prop => (start, end) => start[prop] - end[prop]; | |
const sortedArray = myArr.concat().sort(ascendingProp('id')); | |
// unfortunately if we want this to be descending we run into some trouble. | |
// we can create a funciton, which take a function, | |
// then takes two parameters and flips them in execution | |
const flip = func => (first, second) => func(second, first); | |
const descendById = flip(ascendingProp('id')); | |
const descendingArray = myArr.concat().sort(descendById); | |
console.log(sortedArray); // result: [{ id:1, name: 'chris'}... etc] | |
console.log('descending', descendingArray); // result: [{ id: 6, name: 'matt'}... etc] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment