Destructuring ES6 lambda signatures for fun and profit

Nicholas Johnson
Sep 25, 2018 · 2 min read

Say we have an array like this:

pigs = [
{id:6, name: 'peppa'},
{id:44, name: ‘george’}

Assume I wanted all the ids in an array. We can do this with a regular old map:

var ids = { 

This is going to give us an array like so:

[6, 44]

=> Lambdas

We can improve on this with a fat-arrow lambda function:

const ids = =>;

I’ve replaced the ES5 callback function with an ES6 fat arrow. Because there’s only one argument, I can omit the braces. Because there’s only one line, I can use the implied return statement.


For maximum effect, we can destructure the lambda arguments, like so:

const ids ={ id }) => id);

The curlies in the function signature pull the id field right out of the pig. I think this is rather fine.


We can do a similar thing with find. Let’s say I wanted to get only Peppa:

const peppa = pigs.find(({ name }) => name === ‘peppa’);

It’s like a little query language, just for us.


we can also Filter. Here’s a topPig function that will find all the pigs where the id is greater than some value that I’m calling minId:

const topPigs = (minId) => pigs.filter(({ id }) => id > minId);

Filtering by more than one parameter

This becomes even more useful when we are interested in more than one value. Say we want to find all the pigs where name === ’peppa’ and id > 12:

pigs.filter(({ id, name }) => name === 'peppa' && id > 12)

For each pig, such that I have the id and name, get me pigs where name === ‘peppa’ and id > 12.

Filtering by nested parameters

We can do more. We can also destructure nested parameters. Say we modify our pig array to be like so:

const animals = [
name: ’peppa’,
family: {
mother: ‘mummy pig’,
father: ‘daddy pig’
name: ’suzy sheep’,
family: {
mother: ‘mummy sheep’,
father: ‘daddy sheep’

Let's say I want to find all the animals such that === ‘mummy pig’. I can totally do this too, and it’s not even that hard. I just have to nest the curlies:

animals.filter(({ family: { mother } }) => mother === 'mummy pig');

Combining filters and maps

Now let's say, I want only the names of those animals. I can just chain a map:

animals.filter(({ family: { mother } }) => mother === 'mummy pig')
.map(({ name }) => name);

This will give me an array like so:


Nicholas Johnson

Written by


Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade