JavaScript Array Methods & ES6

by Caroline Shaw on

As a front-end developer, much of my job is grabbing JSON data and manipulating it. While there are a number of fancy array methods to take care of sorting and delivering our JSON data in a readable way, ES6 introduced a few new snazzy ways to express this in a concise way. If you’re like me and don’t find articles that use generic examples “foo” and “bar” particularly useful, let’s look at a real world example of how these array methods & ES6 can help you isolate, modify and organize data for display.

For my dummy data, I’ve borrowed the current Bixi Bikeshare JSON plan data from the City of Toronto’s open data website. Here’s that array of plan objects that I want to organize & display at some point:

const plans = [{  
            "plan_id":"186",
            "name":"Annual",
            "currency":"USD",
            "price":"101.70",
            "is_taxable":1,
            "description":"Annual"
         },{  
            "plan_id":"188",
            "name":"24 Hour",
            "currency":"USD",
            "price":"7.91",
            "is_taxable":1,
            "description":"24 Hour"
         },{  
            "plan_id":"189",
            "name":"72 Hour",
            "currency":"USD",
            "price":"16.95",
            "is_taxable":1,
            "description":"72 Hour"
         },{  
            "plan_id":"190",
            "name":"Annual PRESTO",
            "currency":"USD",
            "price":"61.02",
            "is_taxable":1,
            "description":"Annual PRESTO"
         },{  
            "plan_id":"191",
            "name":"City of Toronto",
            "currency":"USD",
            "price":"90.00",
            "is_taxable":1,
            "description":"City of Toronto"
}];

.map()

Here is the full/non-ES6 syntax for the method .map() from MDN:

var newArray = array.map(function callback(currentValue, index, array) {
    // Return element for newArray
}[, thisArg] // Optional value to use as 'this' when 
             // executing callback 
);

Callback: ([currentValue [, index[, array]]])
(See .map() on MDN)

An aside: If you you're not familiar with the [, thisArg] syntax, you're not alone! The brackets mean that the argument is optional. The comma is included if the argument is included. What are the origins of this syntax?

Screen-Shot-2017-11-28-at-1.04.43-PM--2-
Gemma tipped me off that this syntax could be borrowed from Linux man pages. I read somewhere that it could be loosely based on regex. WE MAY NEVER KNOW. Or perhaps we will find out in another blog post.

Moving on, let’s say I just want to grab all of the titles for our Bixi bike plans to eventually display them as a list of links on a webpage. The map() array method is handy since it loops over our objects and returns a new array, in this case - just the titles.

const planTitles = plans.map(plan => plan.name );

If we logged planTitles to the console, we'd get the following array:

["Annual", "24 Hour", "72 Hour", "Annual PRESTO", "City of Toronto"]

We can also use map() to return an array of modified data. If, for example, we’re looking to make a list of the approximate Canadian prices, we can use map() to run this calculation with the exchange rate.

const cadPrices = plans.map(plan => plan.price * 1.27 + " CAD" );

The output of cadPrices will be:
["129.159 CAD", "10.0457 CAD", "21.5265 CAD", "77.4954 CAD", "114.3 CAD"]

Again, we’re receiving a brand new array based on data from our original dataset.

You'll notice I'm opting to use the fat arrow ES6 => syntax. I'll talk briefly about that now!

ES6 Arrow Functions

Througout my examples I'm using the ES6 => fat arrow syntax. Some advantages to these ES6 arrow functions:

  • They are more concise than regular functions, as you remove the word function
  • They can have implicit returns (you don't always have to write return when you want to return a value)
  • It doesn't rebind the value of this, so it inherits this from the function scope it's nested in!

I don't always use the ES6 arrow function because I'm not totally used to parsing it yet. Sometimes I'll refactor my code so it uses the ES6 code after I've tested it, or when it's simple enough that it's still readable to me at quick glance. Like any language, there's a small adjustment period to getting used to practicing new grammar/skills.

For more information, the MDN docs on arrow functions are very thorough.

.filter()

The next array method I will look at, the .filter() method, also returns a new array. This time it loops through your data and only returns items that pass a test.

var newArray = arr.filter(callback[, thisArg])

Callback: ([element[, index[, array]]])
(See .filter() on MDN)

Let's say we want to only display plans that are under $50. We can run a simple filter:

const cheapestPlans = plans.filter(plan => plan.price < 50 );

Our output of cheapestPlans:

[[object Object] {
  currency: "USD",
  description: "24 Hour",
  is_taxable: 1,
  name: "24 Hour",
  plan_id: "188",
  price: "7.91"
}, [object Object] {
  currency: "USD",
  description: "72 Hour",
  is_taxable: 1,
  name: "72 Hour",
  plan_id: "189",
  price: "16.95"
}]

.every()

arr.every(callback[, thisArg])

Callback Signature: ([currentValue[, index[, array]]])
(See .every() on MDN)

There are some handy array methods that return a true or false that can be used to do simple checks on your data.

For example, if we want to check that all plans are using the USD currency we can use every().

const usdPlans = plans.every(plan => plan.currency == "USD" );

In this case, the output will be true.

.some()

arr.some(callback[, thisArg])

Callback: ([currentValue[, index[, array]]])
(See .some() on MDN)

Similarly, we can check if some of our plans match our requirements. Here, we're asking if any of the plans are not taxable.

const isNotTaxable = plans.some(plan => plan.is_taxable == 0 );

The output will be false.

.reduce()

arr.reduce(callback[, initialValue])

Callback: (previousValue, currentValue, index, context)
(See .reduce() on MDN)

According to MDN:

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

Reduce is very useful for grabbing values within objects and adding them up. For our reduce() method, we're going to loop through each plan to add all of the plan prices up.

const planPricesCombined = plans.reduce((prev, curr, index) => {
    return prev + Number(curr.price);
}, 0);

Output: 277.58

There's also a reduceRight array method that I haven't used yet!
Check it out here.

.findIndex()

arr.findIndex(callback[, thisArg])
Callback: ([element[, index [, array ]]])
See .findIndex() on MDN:

Sometimes you need to find the index of an object, so you can update values! With findIndex() you can easily locate the index of an object based on one of its values.

var findAnnual = plans.findIndex(plan => plan.name == "Annual");

.find()

arr.find(callback[, thisArg])

Callback: ([element[, index [, array ]]])
See .find() on MDN:

You can also isolate a plan based on one of its values, and return:

the value of the first element in the array that satisfies the provided testing function.
MDN

Let's grab the object with the name City of Toronto so we can display its plan details on a new page.

var torontoPlan = plans.find(plan => plan.name == "City of Toronto" );

Output:

{
  currency: "USD",
  description: "City of Toronto",
  is_taxable: 1,
  name: "City of Toronto",
  plan_id: "191",
  price: "90.00"
}

.includes()

Another handy item for when you're searching for a specific term, is the includes() method. It returns a true or false.

arr.includes(searchElement[, fromIndex])

See .includes() on MDN

const hasAnnual = planTitles.includes("Annual PRESTO");

Output: true

I use many of these array methods regularly when building on our various react apps at WonderProxy, and continue to source new ones on Mozilla's directory of handy array methods when necessary. From time to time I need to look at examples to revise how to use these methods, so this blog post aims to be a helpful source for when you're wondering how reduce() works for example.

You can play around with these array methods yourself here: https://jsbin.com/vuhagiheda/edit?js,console,output
If you found this blog post helpful, or not helpful, let me know!

Tutorial JavaScript