Take Care of Yourself & Others. Tips & Resources. #COVID19

Blog: Filtering Arrays with Fat Arrows

Manny Becerra as a child

August 2017

There's various ways to slice-and-dice data in JavaScript. One utility that I have found super helpful though, is the filter method, particularly, when combined with ES6 fat arrows =>.

As a quick rundown

  • The filter method creates a new array filled with all array elements that pass a test
  • ES6 fat arrow functions, =>, are a shorter syntax compared to current function expressions, e.g. function(args) {...}. In addition, ES6 fat arrow functions lexically bind this so you don't, for example, have to save this to that in a variable.

Here's a before and after example of using filter with a fat arrow function =>.

Before

'use strict';

// An an initial list of numbers
let myNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];

let preEs6OddNumbers = myNumbers.filter(function(number) {
  return number % 2;
});

// preEs6OddNumbers would contain all odd numbers, e.g. [1, 3, 5, 7, 9, 11, 13]

After

'use strict';

// An an initial list of numbers
let myNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];

let Es6OddNumbers = myNumbers.filter(number => number % 2)

// Es6OddNumbers would contain all odd numbers, e.g. [1, 3, 5, 7, 9, 11, 13]

Both approaches accomplish the same thing, the ES6 way is just shorter-and-sweeter. Also, in the above example, it's worth noting, that when using an expression after a fat arrow arrow =>, the return is implicit, so you don't have to specify return.

I work with lots of data, especially when working with rich, user interfaces, so every little bit of less code I have to write, because the internal API has it taken care of through implied meaning, the better: it helps bring down file size and gives me back another second or few to re-focus my attention on another task or or UI/data problem to solve — it all adds up.

For a more detailed spec on the filter method and any polyfills you may need to leverage the filter method, check out Mozilla's MDN web docs.

Do you have any code nuggets or ES6 gems that you particularly find useful?

Code on,

Manny


I have a passion and successful track-record for creating usable, online, experiences with a focus on web standards, modularity, education, accessibility, and inclusion. I recruit, on-board, lead, and mentor happy, productive and empathetic cross-functional teams — for onsite, distributed (remote) and hybrid structures — within a continuous learning culture. I am a father, speaker, advisor, life-long learner, community builder, advocate and a Human Being. Learn more.