Most Common Array Methods in ES6

In this article we will take a look into how we can loop into array using ES6 syntax in Javascript and differentiate how it was achieved in older days.

Image for post
Image for post
ECMA

Javascript ES6 in 2015 has brought new syntax and new features to make our code more modern and readable. These changes allows us developers to write less and do more. ES6 brought great features like arrow functions, template strings, modules, array and object destructing, promises, rest parameter and many more.

But in this article we will be just focusing on most popular useful methods for working with Arrays like .map() .filter() and .reduce(). Which are all also referred as higher order functions. Which means that they are a function which returns functions as a result or takes other function as parameters.

.map()

This method creates a new array which populates the results of calling a provided function on every element in the call.

Let’s assume we have an array which consists of work experience of employees in years.

const nrsCurrency = [70000, 5000, 80000, 1000000, 6000, 20000]

If we want to return the value which is in years above six years and over we would write something like below:

let dollarConversion = [];
nrsCurrency.forEach(currency => {
dollarConversion.push(currency * 119.078)
Math.round(dollarConversion)
})

Lets write same function with .map() method, which looks like this below:

const dollarConversion = nrsCurrency.map(currency => (Math.round(currency * 119.078)));

In the above function

  • As a parameter we passed a function
  • The function above takes one parameter (currency)
  • The parameter refers to the current element being iterated in the filter()’s forEach.
  • Function we pass returns a value and insert in the new array.

.filter()

The method does exactly what it says — it takes the existing array and returns a part of that specific array back or probably take out the items we don’t want.

Lets take an example below

const pays = [
{ employee: 'Jack Simmon', salary: '130000' },
{ employee: 'Linda Furnace', salary: '520000' },
{ employee: 'Simp Simson', salary: '70000' },
{ employee: 'Mesa Gradcost', salary: '200000' },
{ employee: 'Alina Haldel', salary: '120000' },
{ employee: 'Jonny Cash', salary: '40000' }
]

In the objects which are inside an Array represents salary of the employees. Let’s assume if we want employees who are highly paid. We can write that function in old way like

let wellPaid = []
pays.forEach(salary => {
if (pays.income >= 100000) {
wellPaid.push(salary)
}
else []
})

Now lets see how we can write same statement with the help of .filter() method

const wellPaid = pays.filter(salary => salary.income >= 100000)

In the above function

  • As a parameter we passed a function
  • The function above takes one parameter (salary)
  • The function we passed returns a boolean as a value. That boolean value indicates weather the current element is filtered out or not. true stays in the array but false is skipped from the array

.reduce()

The reduce() method executes a reducer function (that we provide) on each element of the array, resulting in a single output value.

This means, the function uses the information from the array and calculates something out of it. What will be calculated solely on the function we give it.

Let suppose we went shopping and bought some hardware and gaming gadgets. Our shopped products looks something like

const shoppedItems = [
{ name: 'XBOX', price: 310 },
{ name: 'Gaming Chair', price: 120 },
{ name: 'Joystick', price: 120 },
{ name: 'Witchcraft', price: 220 },
{ name: 'Cyberpunk', price: 295 }
]

In the above array we added some shopping items we shopped. Now let’s make a function which will takes all the price inside those object and spits out the total purchase amount without using reduce method.

let totalPurchase = 0
shoppedItems.forEach(purchase => {
totalPurchase += purchase.price
})
console.log(`$` + totalPurchase)

Now, let’s use our reduce method and rewrite this function in more clear and shorter way.

let totalPurchase = shoppedItems.reduce((total, shop) => total + shop.price, 0)

In the above function

  • The method iterates through the objects and calls our function in every loop.
  • Our first parameter total spits out total in each loop.
  • Shop is current item that is having its loop.
  • The value is returned of our passed function whenever we need to do our total calculation with our total and currentValue.

Conclusion

It bit complicated to master and learn array methods, which will gradually improve our code along our coding phases. So, in summary

.filter() is used when we want to filter out some items from an Array.

.map() is used when we want to create a new array destroying the current one with new values.

.reduce() is used when we want to return a single calculated value.

Written by

Product Designer and Frontend Developer | https://twitter.com/ishan02016

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store