A Simple Guide to JavaScript Array Methods
Tags: career, javascript, webdev, beginners
Published: 2020-11-19 18:15:36

---
series: JavaScript For Total Novice or Beginners.
title: A Simple Guide to JavaScript Array Methods
published: true
description: An introduction to Javascript array methods, 	array methods javascript and array methods in javascript
tags: career, JavaScript, webdev, beginner
//cover_image: https://direct_url_to_image.jpg
---

Welcome to this lesson, in this lesson, we will discuss JavaScript Array Methods.

In the last lesson, we pointed out some JavaScript Array Methods but now, we are going to explain them in details.

Let's start with:

# reverse() method

I was recently on a queue at a bank in Nigeria and I was the last person on the queue while I was in a hurry.

Let's assume the queue is below:

```js
let arrayOfPeople = ['Ope', 'Dupe', 'Ola', 'Ariyo', 'Temi', 'Ayobami'];
```

While on the queue, I felt like using JavaScript to move myself to the beginning of the queue.

The question now is, how can I reverse the array using JavaScript?

That is why we have reverse() method and I could simply do:

```js
 let reversedArrayOfPeople = arrayOfPeple.reverse();
console.log(reversedArrayOfPeople) // ['Ayobami','Temi','Ariyo', 'Ola', 'Dupe', 'Ope'];

console.log(arrayOfPeople) // ['Ayobami','Temi','Ariyo', 'Ola', 'Dupe', 'Ope'];
```	

The reverse method rearrages the elements of the calling array object in descending order, mutates[changes] the array, and returns a reference to the array.

This means arrayOfPeople is reversed and its reference is returned as the value of reversedArrayOfPeople which means changing the value of reversedArrayOfPeople will also change the value of arrayOfPeople because the value of reversedArrayOfPeople is a reference of arrayOfPeople. In short, they are tied together.

For example,
```js
let arrayOfFriends = ['Ope', 'Ayo'];
console.log(arrayOfFriends) // Ope, Ayo
let reversedArrayOfFriends = arrayOfFriends.reversed();

console.log(reversedArrayOfFriends) // Ayo, Ope;
console.log(arrayOfFriends) // Ayo, Ope

// array of people has been affected
```

```js
reversedArrayOfFriends.pop
console.log(reversedArrayOfFriends) // Ayo;
console.log(arrayOfFriends) // Ayo;
```

Do you see that?

Changing reversedArrayOfFriends affect arrayOfFriends because the value of reversedArrayOfFriends is a reference to arrayOfFriends.

The reverse() array method sorts elements of an array in descending order.

# map() method

The map() method is used to iterate over an array of elements to build and return a new array out of it. 

It gets and calls a provided function on each of the elements in a given array one after another.

```js
Array.map(callback, thisValue);
```

The map() method takes two parameters as in above:

Each of the elements in the given array will be passed to the callback function as a parameter. 

Basically, the callback function has three parameters: currentArrayElement (currentValue), indexOfTheElement (optional) and theArrayItself (Optional).

```js
 Array.map(function(currentValue, index, array) {
  
  }, thiValue)
```

In short, the callback function provides us with the current element, its index and the array itself.

```js
let persons = [
   { name: "Buhari", friendship: false}, 
   { name: "Obama", friendship: false}, 
   { name: "Trump", friendship: false}
];

let friends = persons.map(function (person) {
   person.friendship = true;
   return person;
}); 
```

We can also use the fat-arrow function to be more concise as in:

```js

let numbers = [2, 3, 4, 5];

let squaredNumbers = numbers.map( number => number * number ); 
```

Both native and fat-arrow functions can be used with the map() method interchangeably except when the thisValue parameter of the map() method is needed because we cannot bind the fat-arrow function and so thisValue will not be accessible within the fat-arrow function.

What is thisValue?

In an object, this is used to reference the context of an operation. If a "this" is needed, for some reasons, within the callback function, thisValue is used to supply the context to the callback.

For example, you need to supply "this" to map() when it is used in an object or anywhere "this" is needed for access as in:

```js
let me = {
    persons : [
       { name: "Buhari", friendship: false}, 
       { name: "Obama", friendship: false}, 
       { name: "Trump", friendship: false}
    ],
 
    name: "Ayobami",
    makeFriends: function(){
       this.persons.map(function(person) {
          person.friendship = true;
       }, this)
    }
};

me.makeFriends();
me.persons
```

Better still, we can supply the variable person in place of this when it is not within the object as in:

```js
let persons = [
       { name: "Buhari", friendship: false}, 
       { name: "Obama", friendship: false}, 
       { name: "Trump", friendship: false}
    ];

let me = {
    name: "Ayobami",
    makeFriends: function(){
       persons.map(function(person) {
          person.friendship = true;
       }, persons)
    }
};

me.makeFriends();
me.persons
```

# Caveat

The map() array method shouldn't be used when there is no need to return a value or an array. forEach() or for(...in) should be used instead.

Map() can't be used on an empty array.

# forEach() method

The forEach() method is very similar to the map() method in structure:

```js
 Array.forEach(function(currentValue, index, array) {
  
  }, thiValue)
```
They are different in operation and function. forEach() doesn't create a new array but changes/mutates the array it loops through unlike the map() method.

That is why forEach is mostly used when their is a need to mutate variables right from the callback function as in:

```js

//You need to first add an HTML element with friendBox as its ID to you HTML code.
<div id="friendBox"></div>


let friends = ["Obama", "Trump", "Buhari"];
friends.forEach(showFriends);

function showFriends(friend, index) {
  document.getElementById("friendBox").innerHTML += index + ":" + friend + "<br>";
}
```
Let's count the total number of friends as another example:

```js
let friends = ["Obama", "Trump", "Buhari"];
let numberOfFriends = 0;

friends.forEach(countFriend);

function countFriend(friend, index) {
  console.log(friend);
  numberOfFriends++
}
```
forEach() is very handy when you need to mutate/change a state.

# filter() method

The filter() method creates a new array using every element that passes a test and then returns the final array. 

It is very similar to the map() method in structure:

```js
 Array.filter(function(currentValue, index, array) {
  
  }, thiValue)
```

Filter() in action:

```js

let numbers = [1,2,3,4];

let numberGreaterTwo = numbers.filter( number => number > 2 ); //[3,4] 
```
So, the above create a new array and inserts all the numbers that pass the test - any number that is greater than 2.


# toString() Method

Sometimes, you may need to display the elements of an array as a text (string). In that case, you need to use the toString() method to convert the array to a string (text) you want to display to your users.

```js
let arrayOfPeople = ['Ope', 'Dupe', 'Ola', 'Ariyo', 'Temi', 'Ayobami'];
document.getElementById("text").innerHTML = arrayOfPeople.toString();
```

Boom! The elements of the array of people will be displayed in the browser as a text node of an element with "ID" text.

toString() method converts the elements of an array to a string without affecting the array itself. That is, the array remains the same.

# join() Method

The join() method is used to combine the element of an array into a string (text) with a separator such as a comma, a dash -, a space " ", no-space "", plus +, alphabets or anything desired:

```js
let arrayOfFriends = ['Ope', 'Dupe', 'Ola'];
arrayOfFriends.join("") // OpeDupeOla;

arrayOfFriends.join(" "); // Ope Dupe Ola;

arrayOfFriends.join("_"); // Ope_Dupe_Ola;

arrayOfFriends.join("-"); // Ope-Dupe-Ola;

arrayOfFriends.join("a"); // OpeaDupeaOla;
```

By default, that is, if you don't use any separator with the Join() method, comma (,) will be used:

```js
let arrayOfFriends = ['Ope', 'Dupe', 'Ola'];
arrayOfFriends.join(); // Ope,Dupe,Ola
```

Note: Using the join() method on an array does not change the array.

# splice() method 

splice() method can add and remove elements from an array.

```js
splice( startIndex, deletCount, ItemToBeAdded1, ItemToBeAdded2, ItemToBeAddedn -1);
```

The first parameter (start) specifies the index - starting from zero - where an element should be inserted or removed. 

The second parameter (deletCount) specifies the total number of elements to be removed starting from the start index provided. 

The remaining parameters set the values that will be added to the array.

For example,

```js
let friends = ['Ope', 'Dupe', 'Ola'];
//Adds Ayobami to the array of friends at index 3.
friends.splice(3, 0, 'Ayobami');// Ope, Dupe, Ola, Ayobami
```

From the above splice() method, deleteCount is set to 0, so we don't delete any element but we only add 'Ayobami' to the array at index 3 counting from 0.

```js
let days = ['Monday', 'Wednesday', 'Thursday'];
//Adds Tuesday to the array of days at index 1;
day.splice(1,0, 'Tuesday);// Monday, Tuesday, Wednesday, Thursday
```

From the above splice() method, deleteCount is set to 0, so we don't delete any element but we only add 'Tuesday' to the array of days at index 1 counting from zero;

```js
let days = ['Monday', 'Tuesday', 'June', 'July', 'Wednesday'];

/* remove 2 elements starting from index 2 and then add 'Thursday and Friday' starting from index 2 also.*/

days.splice(2,  2, 'Thursday', 'Friday');// Monday, Tuesday, Wednesday, Thursday, Friday.

let days = ['Monday', 'Tuesday', 'June', 'July', 'Wednesday'];
//remove 2 elements starting from index 2.
days.splice(2, 2); // Monday, Tuesday, Wednesday;
```

In short, the splice() method can be used to add or remove an element or elements from an array at the same time or at different time.

- If deleteCount is 0 or negative, no element is removed.
- If an element to be added is not specified, splice() will only remove element(s).
- "If deleteCount is is equal to or greater than the number of elements left in the array, starting at start), then all the elements from start to the end of the array will be deleted." -MDN. E.g 

```js
let names = ['Ayo', 'Ope', 'Ola'];
//delete 3 elements from names starting at index 0 (from the beginning)
names.splice(0, 3) // []

//delete 3 elements from names starting at index 1
names.splice(1, 3) // Ayo 
// Ayo is not removed because it has index zero.
```
Check whether you understand these:

- splice(2, 0, 'Element') // add 'Element' at index 2.
- splice(2, 1) // remove an element at index 2.
- splice(2, 0, 'Ayobami', 'Ope') // what does it mean?
- splice(0, 0, 'Ayobami) // what does it mean?

```js
let days = ['Monday', 'Tuesday', 'June', 'Wednesday'];
days.splice(2, 1); // what will happen? You can check it in the console.

days.splice(0,5) // what will happen? You can check it in the console.
```

# slice() Method

splice() method can add and remove elements from an array.

```js
slice([ start[, end]]);
```

Slice() creates a new shallow copy of an array by selecting the elements starting at the given start argument, and ends at the argument next to the given end argument.

```js
let friends = ["Ope", "Ayo", "Tola"]; 

//starts from the beginning and ends at the index before the given end argument.
let goodFriends = friends.slice(0, 2);  // Ope, Ayo;
starts from the beginning and ends at the index before the given end argument.
let richFriends = friends.slice(0, 3) // Ope, Ayo, Tola;
```

# concat() Method
JavaScript concat() method combines two arrays to a new array (a shallow copy of the array). It can take any number of arguments:

```js
let friends = ["Ope", "Ayo", "Tola", "Wale"]; 
var richFriends = ["Prosper", "Celestine"];  
var combinedFriends = friends.concat(richFriends);      
console.log(combinedFriends) // Ope, Ayo, Tola, Wale, Prosper, Celestine
```
Note: Using the concat() method on an array does not change the array, it only returns a new array created.


# indexOf() Method

```js
array.indexOf(elememt, start);
```
The indexOf method searches an array for an element from the start  to the end of the array and returns the position/index of the element if it is found or -1 if it not found.

We can also set the starting point for the search.

```js
let friends = ["Obama", "Trump", "Buhari"];
let indexOfTrump = friends.indexOf("Trump");// 1
```

# lastIndexOf() method

```js
array.lastIndexOf(element, start);
```
The lastIndexOf method searches an array for an element from the end to the start of the array and returns the position/index of the element if it is found or -1 if it not found.

We can also set the starting point for the search.

```js
let friends = ["Obama", "Trump", "Buhari", "Ayobami"];
let indexOfTrump = friends.lastIndexOf("Buhari");// 2
```	
# include() method

```js
array.includes(element, start)
```
The include() method is used to check whether an array contains an element or not. It returns true if it is found but returns false if it is not found. include() is case sensitiv 

```js
let friends = ["Obama", "Trump", "Buhari", "Ayobami"];
friends.includes("Trump");// true
```

# find() method

```js
Array.find(function(currentValue, index, array) {
  
  }, thiValue)
```
It returns the value of the first element in an array that passes a test provided.

```js
 let numbers = [1,2,3,4,5,6,7];
numbers.find(number => number > 3);// 4
```

# findIndex() method

```js
Array.findIndex(function(currentValue, index, array) {
  
  }, thiValue)
```

It returns the index of the first element which passes a test provided.

```js
let numbers = [1,2,3,4,5,6,7];
numbers.findIndex(number => number > 3);// 3
```

# isArray() method

```js
array.isArray(obj);
```

It checks whether an object is an array or not. If it is an array, true is returned but false is returned if it is not an array.

```js
let numbers = [1,2,3,4,5,6,7];
Array.isArray(numbers)// true
```
That is it.

See you in the next lesson.

# One more thing

Are you having difficulties to learn and understand JavaScript and build projects with it? ***JavaScript for a Total Novice*** teaches JavaScript and Project Making Fundamentals with simple illustrations and examples that make everything so easy. You can now handle any difficult projects without fear.

Don't trust me, get a free previous to judge by yourself: https://bit.ly/3o3TMyg