Beginner's guide to Javascript arrays [PART 2]
Tags: javascript, beginners, webdev
Published: 2019-08-18 11:44:07

---
title: Beginner's guide to Javascript arrays [PART 2]
published: true
description: Diving a little deeper into array methods
tags: javascript, beginners, webdev
cover_image: https://thepracticaldev.s3.amazonaws.com/i/bdjhfllo4ulpzp62gwi1.png
---

Hi guys! First of all I am more than overwhelmed by the reception the predecessor of this post received. It really do appreciate.
If you're viewing this for the first time, be sure to check out the PART 1 of this post [Here!](https://dev.to/simplytammy/beginner-s-guide-to-javascript-arrays-part-1-1p2n).

We will consider the following methods for this post.

* reduce()
* map()
* filter()
* sort()

Let's dive right in.

First of all let's define an array (or two) that we will be using for this.

```javascript

// Array 1

const students = [

{firstname: 'Tammy', lastname:'Benjamin', admitted: 2011, graduation: 2014},
{firstname: 'Deborah', lastname:'Emeni', admitted: 2017, graduation: 2021},
{firstname: 'Daniel', lastname:'Oke', admitted: 2009, graduation: 2012},
{firstname: 'Ogurinka', lastname:'Benjamin', admitted: 2012, graduation: 2016},
{firstname: 'Nelson', lastname:'Abel', admitted: 2017, graduation: 2021},
{firstname: 'Ellie', lastname:'Julie', admitted: 2013, graduation: 2017},

];


// Array 2

const teachers = [

'Stephen', 'Richard', 'Biodun', 'Ruth',
'Peter', 'Paul', 'John', 'Jacob', 'Chris',
'Emeka', 'Nicole', 'Jaden', 'Albert',

];

```

Array 1 holds an array of objects (Read about objects [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)) of specifying the names, year of admission into school and year of graduation.

Array 2 holds a basic array of teachers.


Let's assume we want to get the list of students admitted in the year 2017 from the array, this can be achieved using the **_filter()_** method

## What is the filter() method ?

The filter() method creates a new array with array elements that passes a test. This is useful for accessing properties, in the case of objects. If the current item passes the condition, it gets sent to the new array. 
In the exercise above, we want to get the value of a specific property in our object array, in this case every student admitted in 2017

Code:

```javascript

const admittedIn2017 = students.filter(function(student) {

if (student.admitted === 2017) {
return true;

}

});

console.log(admittedIn2017);


```

Explanation:

The above iterates over the entire array and checks for every occurrence where the value of admitted is 2017 and then returns the object which we display to the console.
We take the students array and filter over it. The filter method takes in a function which has an argument. We use this argument to make reference to the property in our object(in this case 'admitted') and  then set our condition.For every time the condition is passed, the function returns true.

Challenge:

As a personal challenge, add more array items and try to return every student that will graduate within a range of year (say between 2012 to 2021)


## map()

Let's assume you want to get the first name and the year of admission of every student in our array, we can achieve this using the **_map()_** method.

The map () method creates a new array by performing a function on each array element. In our case we want to get every student's first-name and their year of graduation.
It is important is important to note that the new array has the same length as its original.


Code:

```javascript

const firstNameAndGradYear = students.map(function(student) {

return student.firstname + " " + student.graduation;

});


console.log(firstNameAndGradYear);

```

Explanation:

Here we are iterating over our student array and returning the value of 'firstname' and 'graduation' of each object and then displaying it to our console.


Challenge:

Try returning the last name and first name of every student. (Quite simple)



## sort()

The **_sort()_**  method sorts an array based on a certain condition and returns a new array.

Let's assume we want to sort our students array based on their year of graduation


Code:

```javascript

 const aphabetically = students.sort(function(a, b) {

if (a.firstname > b.firstname) {

  return 1;
}
else {

return -1;
}

});


console.log (aphabetically);



```

Explanation:

The above iterates over our students array and compares all first names . It checks and sorts our students array alphabetically based on their first names. It takes two arguments (a,b) and moves it up or down based  on alphabetical order

Challenge:

Try to sort the array based on the year of graduation order.


## reduce()

The **_reduce()_** method runs a function on each array element to reduce it to a single value.

To understand this better, we will try to verify how many years all students in our array will spend in school.

Code:

```javascript

const yearInSchool = students.reduce(function(total, student) {


return total + (student.graduation - student.admitted)


}, 0);

console.log(yearInSchool);

```

Explanation:

We iterate over our array and output the combined number of years all the students in our array will be spending in school. The 'total' argument here serves as an accumulator which we assign an initial value of 0 and each time we iterate over our array, is given the value of our math operation (student.graduation - student.admitted). You can read more about it and how it works [here!](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)

Challenge:

Try to get the amount of years all the students graduating in 2021 alone will be spending in school



## Additional array methods

There a few other array methods which can also prove useful in different scenarions



### toString()

This converts an array into a string.

Usage: (Using our Teachers array)


```javascript

teachers.toString() // Converts the teachers array to string separated by a comma


```


### join()

It behaves just like toString(), but in addition you can specify the separator


Usage:

```javascript

teachers.join('/'); // Converts the teachers array to string separated by a forward slash

```

### every()

The every() method check if all array values pass a test.

Example: Using our student array

For example, we will try to check if all the year of admission of our students array is greater than 2011

```javascript

const greaterThan2011 = students.every(function(student) {
return student.admitted >= 2011;
});
console.log(greaterThan2011); // will return false


```


### some()

The some() method check if some array values pass a test.

Example: Using our students array


```javascript

const greaterThan2011 = students.some(function(student) {
return student.admitted >= 2011;
});
console.log(greaterThan2011); // will return true


```
### find()

The find() method returns the value of the first array element that passes a test function


Example: Using our students array


```javascript

const greaterThan2011 = students.find(function(student) {
return student.admitted >= 2011;
});
console.log(greaterThan2011);


```


### indexOf()


The indexOf() method searches an array for an element value and returns its position. It takes two arguement, the item to search for(which is required) and where to start the search. Negative values will start at the given position counting from the end, and search to the end (which is optional)

Example: Using our teachers array

```javascript

console.log(teachers.indexOf("Biodun")); // returns 2

```

### lastIndexOf()

This is the same as indexOf(), but returns the position of the last occurrence of the specified element.

### includes()

The includes() method determines whether an array contains a specified element.

Example: using our teachers array


```javascript

console.log(teachers.includes("Biodun")); // returns true

```



## Summary

There are dozens more array methods that you can find useful depending on the task you intend to accomplish. I have taken out time to list out the ones I have had reasons to use and I hope you picked up a thing or two from this. Thank you.