Skip to content

Instantly share code, notes, and snippets.

@williamcspace
Created August 31, 2016 09:53
Show Gist options
  • Save williamcspace/4318865c6151993446b3c2ddc53cc8ba to your computer and use it in GitHub Desktop.
Save williamcspace/4318865c6151993446b3c2ddc53cc8ba to your computer and use it in GitHub Desktop.
practical functional array operations
// 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' ]
// 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]
//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
// 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