Created
August 31, 2016 09:53
-
-
Save williamcspace/4318865c6151993446b3c2ddc53cc8ba to your computer and use it in GitHub Desktop.
practical functional array operations
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
// When: You want to remove unwanted elements based on a condition. | |
// Example: remove duplicate elements from an array.\ | |
const names = ['will', 'bill', 'william', 'bill', 'william', 'will']; | |
const uniqueNames = names.filter((elem, index, arr) => arr.indexOf(elem) === index); // [ 'will', 'bill', 'william' ] |
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
// When: You want to translate/map all elements in an array to another set of values | |
// Example: convert Fahrenheit temps to Celsius. | |
const fahrenheit = [0, 32, 45, 50, 75, 80, 99, 120]; | |
const celcius = fahrenheit.map(elem => Math.round((elem - 32) * 5 / 9)); // [-18, 0, 7, 10, 24, 27, 37, 49] |
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
//when: You want to find a cumulative or concatenated value based on elements across the array. | |
//Example: Sum up orbital rocket launches in 2014. | |
const rockets = [ | |
{ country:'Russia', launches:32 }, | |
{ country:'US', launches:23 }, | |
{ country:'China', launches:16 }, | |
{ country:'Europe(ESA)', launches:7 }, | |
{ country:'India', launches:4 }, | |
{ country:'Japan', launches:3 } | |
]; | |
const sum = rockets.reduce((prevVal, elem) => prevVal + elem.launches, 0); // 85 |
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
// Old way | |
for(var i = 0; i < array.length; i++) { | |
if(array.indexOf(array[i]) === i) { | |
models.push(array[i]); | |
} | |
} | |
// functional way | |
var uniqueProducts = array.filter(function(elem, i, array) { | |
return array.indexOf(elem) === i; | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment