DEV Community

Ayobami Ogundiran
Ayobami Ogundiran

Posted on • Edited on

A Simple Guide to JavaScript Array Methods

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:

let arrayOfPeople = ['Ope', 'Dupe', 'Ola', 'Ariyo', 'Temi', 'Ayobami'];
Enter fullscreen mode Exit fullscreen mode

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:

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

console.log(arrayOfPeople) // ['Ayobami','Temi','Ariyo', 'Ola', 'Dupe', 'Ope'];
Enter fullscreen mode Exit fullscreen mode

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,

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
Enter fullscreen mode Exit fullscreen mode
reversedArrayOfFriends.pop
console.log(reversedArrayOfFriends) // Ayo;
console.log(arrayOfFriends) // Ayo;
Enter fullscreen mode Exit fullscreen mode

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.

Array.map(callback, thisValue);
Enter fullscreen mode Exit fullscreen mode

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).

 Array.map(function(currentValue, index, array) {

  }, thiValue)
Enter fullscreen mode Exit fullscreen mode

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

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;
}); 
Enter fullscreen mode Exit fullscreen mode

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


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

let squaredNumbers = numbers.map( number => number * number ); 
Enter fullscreen mode Exit fullscreen mode

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:

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
Enter fullscreen mode Exit fullscreen mode

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

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
Enter fullscreen mode Exit fullscreen mode

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:

 Array.forEach(function(currentValue, index, array) {

  }, thiValue)
Enter fullscreen mode Exit fullscreen mode

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:


//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>";
}
Enter fullscreen mode Exit fullscreen mode

Let's count the total number of friends as another example:

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

friends.forEach(countFriend);

function countFriend(friend, index) {
  console.log(friend);
  numberOfFriends++
}
Enter fullscreen mode Exit fullscreen mode

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:

 Array.filter(function(currentValue, index, array) {

  }, thiValue)
Enter fullscreen mode Exit fullscreen mode

Filter() in action:


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

let numberGreaterTwo = numbers.filter( number => number > 2 ); //[3,4] 
Enter fullscreen mode Exit fullscreen mode

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.

let arrayOfPeople = ['Ope', 'Dupe', 'Ola', 'Ariyo', 'Temi', 'Ayobami'];
document.getElementById("text").innerHTML = arrayOfPeople.toString();
Enter fullscreen mode Exit fullscreen mode

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:

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;
Enter fullscreen mode Exit fullscreen mode

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

let arrayOfFriends = ['Ope', 'Dupe', 'Ola'];
arrayOfFriends.join(); // Ope,Dupe,Ola
Enter fullscreen mode Exit fullscreen mode

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.

splice( startIndex, deletCount, ItemToBeAdded1, ItemToBeAdded2, ItemToBeAddedn -1);
Enter fullscreen mode Exit fullscreen mode

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,

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

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.

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

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;

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;
Enter fullscreen mode Exit fullscreen mode

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
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.
Enter fullscreen mode Exit fullscreen mode

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?
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.
Enter fullscreen mode Exit fullscreen mode

slice() Method

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

slice([ start[, end]]);
Enter fullscreen mode Exit fullscreen mode

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.

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;
Enter fullscreen mode Exit fullscreen mode

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:

let friends = ["Ope", "Ayo", "Tola", "Wale"]; 
var richFriends = ["Prosper", "Celestine"];  
var combinedFriends = friends.concat(richFriends);      
console.log(combinedFriends) // Ope, Ayo, Tola, Wale, Prosper, Celestine
Enter fullscreen mode Exit fullscreen mode

Note: Using the concat() method on an array does not change the array, it only returns a new array created.

indexOf() Method

array.indexOf(elememt, start);
Enter fullscreen mode Exit fullscreen mode

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.

let friends = ["Obama", "Trump", "Buhari"];
let indexOfTrump = friends.indexOf("Trump");// 1
Enter fullscreen mode Exit fullscreen mode

lastIndexOf() method

array.lastIndexOf(element, start);
Enter fullscreen mode Exit fullscreen mode

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.

let friends = ["Obama", "Trump", "Buhari", "Ayobami"];
let indexOfTrump = friends.lastIndexOf("Buhari");// 2
Enter fullscreen mode Exit fullscreen mode

include() method

array.includes(element, start)
Enter fullscreen mode Exit fullscreen mode

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

let friends = ["Obama", "Trump", "Buhari", "Ayobami"];
friends.includes("Trump");// true
Enter fullscreen mode Exit fullscreen mode

find() method

Array.find(function(currentValue, index, array) {

  }, thiValue)
Enter fullscreen mode Exit fullscreen mode

It returns the value of the first element in an array that passes a test provided.

 let numbers = [1,2,3,4,5,6,7];
numbers.find(number => number > 3);// 4
Enter fullscreen mode Exit fullscreen mode

findIndex() method

Array.findIndex(function(currentValue, index, array) {

  }, thiValue)
Enter fullscreen mode Exit fullscreen mode

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

let numbers = [1,2,3,4,5,6,7];
numbers.findIndex(number => number > 3);// 3
Enter fullscreen mode Exit fullscreen mode

isArray() method

array.isArray(obj);
Enter fullscreen mode Exit fullscreen mode

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.

let numbers = [1,2,3,4,5,6,7];
Array.isArray(numbers)// true
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)