Array Methods

The Array object has many methods which help developers to handle arrays easily and efficiently. And even learning the basics can greatly improve the readability of your code.Here we are going to learn about some of them by working on the below by working on the below example.

let companies = [
  { name: 'Company One', category: 'Finance', start: 1981, end: 2003 },
  { name: 'Company Two', category: 'Retail', start: 1992, end: 2008 },
  { name: 'Company Three', category: 'Auto', start: 1999, end: 2007 },
  { name: 'Company Four', category: 'Retail', start: 1989, end: 2010 },
  { name: 'Company Five', category: 'Technology', start: 2009, end: 2014 },
  { name: 'Company Six', category: 'Finance', start: 1987, end: 2010 },
  { name: 'Company Seven', category: 'Auto', start: 1986, end: 1996 },
  { name: 'Company Eight', category: 'Technology', start: 2011, end: 2016 },
  { name: 'Company Nine', category: 'Retail', start: 1981, end: 1989 },
]

let ages = [33, 12, 20, 16, 5, 54, 21, 44, 61, 13, 15, 45, 25, 64, 32]

Here we have two array’s companies & ages. Companies have few objects with name,category,start and end, And ages have age of peoples in number.We will do examples taking them as reference.

forEach():

The forEach() method executes a provided function once for each array element.It is basically an easier way of looping through an array instead of using for loop. So let’s try to log all the elements inside array companies with a for loop first.

for (let i = 0; i < companies.length; i++) {
  console.log(companies[i])
}

Now lets try it with a forEach() method which will do the same thing.

companies.forEach(company => console.log(company))

If we wanted just the names instead of the complete object we can console log company.name .

filter():

The filter() method creates a new array with all elements that pass the test implemented by the provided function.As the name suggest,it filters things out from an array.Lets do an example to get a better idea of the method. If we want to filter out the age which are more than 21 from ages, we can use this method.Let’s do it with for loop first.

let canDrink = []
for (let i = 0; i < ages.length; i++) {
  if (ages[i] >= 21) {
    canDrink.push(ages[i])
  }
}
console.log(canDrink)

Here we are using for loop to itrate on every element and check if it is less than or equal to 21 and if it is true the element is pushed onto a new blank array canDrink.

The same can be done easily with a filter() method.

let canDrink = ages.filter(age => age >= 21)
console.log(canDrink)

Here we are using this method to make a new array canDrinkwith our required data.It loops through each element and check if the number is less than or equal to 21 and if it is, It stores the value in a new array canDrink which can be seen after console.log(canDrink).

map():

The map() method creates a new array with the results of calling a provided function on every element in the calling array. map() works a bit differently than the filter() and we can create an array of the same size from our current array instead of filtering out. Let’s create a new array of only company names.

let companyName = companies.map(company => company.name)
console.log(companyName)

And thats it, here we are creating an array of just company names with a single line of code with the help of this method. Let’s do another example were we will make an array of company name with their start and end year.

let companyDetails = companies.map(
  company => `${company.name} [${company.start} - ${company.end}]`
)
console.log(companyDetails)

sort():

The sort() method sorts the elements of an array in place and returns the array.So lets use this method to sort companies by their start year.

const sortedCompanies = companies.sort((c1, c2) => c1.start - c2.start)
console.log(sortedCompanies)

Here we are simply comparing values of c1.start and c2.start and will sort the array in ascending order. Lets see another example were we will sort ages in ascending order.

let sortAges = ages.sort((a1, a2) => a1 - a2)
console.log(sortAges)

The above code will do the same thing as sortedCompanies and will compare two variables and creates an array sortAges in ascending order.

reduce():

The reduce() method reduce the values of an array to a single value.It consists of an accumulator and currentValue. The accumulator accumulates the callback’s return values and we have to initialize it with any value or else it will pick the first value from the array.The currentValue if the current element being processed in the array. So let’s go ahead and get the sum of the array ages by using reduce() method.

let ageSum = ages.reduce((total, age) => total + age, 0)
console.log(ageSum)

Here the total is initialized by zero and all the elements are added to total one by one to give us the sum of all the element from array ages. Let’s use reduce() again to get a sum of all the years of companies.

let sumYears = companies.reduce(
  (total, company) => total + (company.end - company.start),
  0
)
console.log(sumYears)

And it will give us the total years as required. Please note we can also chain/combine methods as per our requirements.

Published 22 Jan 2018

I'm a web developer specializing in react. I make things from scratch, love to capture photos, and write about programming.I am currently searching for job as a front end developer.
Sourav Kumar on Twitter