One of the more common tasks when mapping over arrays in JavaScript is extracting properties from objects. Instead of using individual arrow functions, we can create a reusable helper function that does the plucking for us.
const countries = [
{ name: 'France', capital: 'Paris' },
{ name: 'Spain', capital: 'Madrid' },
{ name: 'Italy', capital: 'Rome' }
]
// we can extract the attributes with individual arrow functions
countries.map(country => country.name) // β ['France', 'Spain', 'Italy']
countries.map(country => country.capital) // β ['Paris', 'Madrid', 'Rome']
// this function allows us to write that arrow function shorter
const pluck = property => element => element[property]
countries.map(pluck('name')) // β ['France', 'Spain', 'Italy']
countries.map(pluck('capital')) // β ['Paris', 'Madrid', 'Rome']
Top comments (4)
How about this,
Very nice. I usually use the other one because that way itβs easier to chain with other array methods: .filter() an array, .map() some values out of its elements, .sort() the result, maybe run a .reduce() over it, all in the same chain.
If thatβs not the scenario, I like your solution better.
The magic of partial application
Thank you @domhabersack
This is exactly what I was looking for and I was able to make quick work of large datasets without any use of loops.
Thanks :)