JavaScript Array Methods

JavaScript Array Methods

As you may know, Arrays in programming are sets of data. In many languages arrays only have one data type. In JavaScript Arrays are different. We can create an array which can contain many data types. There are also many methods that we use in JavaScript in order to work with arrays. Let’s start with some of these methods.

Array Length

The array length is the method we use to know the size of length. This method is going to return a number that is the number of elements of the array. That is the array size or length. We can implement that method as any method in JavaScript. We only need to type the name of the array, then we type the method name after a dot. The example below shows how to find the length for any JavaScript array.

let fruits = ['mango', 'Apple', 'Orange', 'Pear'];  // Array Declaration

console.log(fruits.length); 

4 // Result
/***************************************************************************************************/

The Push Method

The next method we are going to see is the push method. This method adds a new element at the end of the array. I mean the new element will be the last element of the array. The array length also changes. That’s because of the new element. You can see another example below.

let cars = ['Honda','Toyota', 'Ford', 'Chevrolet'];  // We declare an array of four elements

cars.push('kia');   //Push Method

console.log(cars);

  ["Honda", "Toyota", "Ford", "Chevrolet", "kia"] // Result of the new array. Length = 5


/*************************************************************************************************/

The Unshift Method

We can also add elements to the beginning of the array. The new element becomes the first of the array. That is possible using the “unshift” method. We have the same “fruits” example we used above. We now are going to use the unshift method, and you will see the changes.

let fruits = ['mango', 'Apple', 'Orange', 'Pear'];    // Array Declaration

fruits.unshift('Banana'); // Unshift Method

console.log(fruits);

["Banana", "mango", "Apple", "Orange", "Pear"] //Result  


Removing Array Elements

Pop Method

As we can add elements to arrays, we can also remove elements. The method to remove the last element of the array is the “pop” method. Once we apply this method the array length will change. The result will be a new array with the last item removed. The example below shows how this method works.

let animals = ['dog','cat','horse', 'squirrel'];  // Declare  the array

animals.pop(); // Applying the pop method

console.log(animals);

["dog", "cat", "horse"] // Result Squirrel removed

Shift Method

The “shift” method is similar to “pop”. Shift method removes the first element of the array instead of the last. This method also returns a new array with the length decreased by one. The example below shows how to implement the shift method.

let oddNumbers = [1,3,5,7,9];

oddNumbers.shift(); //removes 1

console.log(oddNumbers);

 [3, 5, 7, 9]  // New Result

Finding the index of an element

We can find the index of any array element using the “indexOf” method. As we also know the index of array elements start with 0 and then continues. We have a brief example below showing you how to find the index of any element of an array.

let cities = ['Boston', 'Chicago', 'New York', 'Washington', 'Miami', 'Los Angeles', 'San Antonio','Phoenix', 'Las Vegas' ,'Salt Lake City', 'Seattle','Portland'];

cities.indexOf('Washington'); // Applying method to find index 

3 // Result. As you may know arrays start with 0


/**************************************************************************************************************/

Remove Elements by Index

To Remove any element by index, we only need to use the “splice” method. This method is very useful to remove one or more elements. The splice method contains two parameters. The first parameter is the starting position; while the second is the ending position. In the case we only have one parameter that shows the starting position. Everything after that position will be removed. We show you many examples below about the splice method

let easternStates = ['Maine', 'Rhode Island', 'Massachusetts', 'Vermont', 'Connecticut', 'New York', 'New Jersey', 'Pennsylvania', 'Maryland', 'Virginia', 'North Carolina', 'South Carolina', 'Georgia', 'Florida'];
//We first declare the array

console.log(easternStates);

["Maine", "Rhode Island", "Maryland", "Virginia", "North Carolina", "South Carolina", "Georgia", "Florida"] // Result


/****************************************************************************************************************/

Creating a new array from removed items

We can also create a new array from the items we removed using the splice method. Let’s use the same example we saw above to get the new array.

let easternStates = ['Maine', 'Rhode Island', 'Massachusetts', 'Vermont', 'Connecticut', 'New York', 'New Jersey', 'Pennsylvania', 'Maryland', 'Virginia', 'North Carolina', 'South Carolina', 'Georgia', 'Florida']; 
//Declare the Array

let statesRemoved = easternStates.splice(2,6);

console.log(statesRemoved);

["Massachusetts", "Vermont", "Connecticut", "New York", "New Jersey", "Pennsylvania"] //Result

/****************************************************************************************************************/

The Slice Method

The “slice” method for arrays, creates a copy of a portion of any array. It’s similar to the splice method; but it creates a copy of the elements we specify in the parameters. If we only have one parameter, it’s chosen as the starting point. Take note that last parameter is not included in the new array. Let’s see a brief example.

let myFruits = ['Orange', 'Apple', 'Banana', 'Strawberry', 'Pear'];

console.log(myFruits.slice(2)); 
  ["Banana", "Strawberry", "Pear"]. // Only one Parameter  returns everything after the index

console.log(myFruits.slice(2, 4));

["Banana", "Strawberry"]. //  From parameter 2 to 4 where 4 is not included.

Looping through Arrays

Most JavaScript tutorials show how to loop through an array. Perhaps you have seen it before. Looping through an array is one of the most used methods in JavaScript arrays. You know in programming we have many loops. In my opinion the most useful loop for arrays is the “forEach” loop. As you may also know that we need a callback function to loop through an array with the forEach loop. Here we show you the most simple example of how to loop through an array.

let myAnimals = ['dog', 'cat', 'horse','cow', 'goat'];

myAnimals.forEach(function(animal){ 

console.log(animal);

});

//Result
   dog
   cat
   horse
   cow
   goat

Advanced Methods for JavaScript Arrays

We could see above many useful methods for javaScript Arrays. The following methods for JavaScript Arrays are called advanced methods. Don’t get confused; They are not hard to learn. They are called advanced methods because of the tasks they perform. Let us start. dealing with these methods.

Array Filter

The method of array “filter” is going to return a new array with the conditions we set on a function or another method. This method is very easy and useful. We show you a brief example of how it works.

let wildAnimals = ['lion', 'tiger','elephant','cheetah', 'gorilla', 'giraffe'];

let shorterNames = wildAnimals.filter(wildAnimal => wildAnimal.length < 6);

console.log(shorterNames);

["lion", "tiger"] //Result


Sort Array

The “sort” method for arrays sort the array as we instruct it. By default it’s going to sort the array ascending. Then it returns a new array with elements sorted. In cases we have numbers in the array, it transform the numbers to strings. We need to be aware of that because if we have numbers like “25” and “3”, “25” is going to be in a position before 3. That is because it’s treated as string. Also if we have undefined elements any array, the “sort” This method is going leave them to the last positions. Here we show you another brief example of how this method works.

let myNumbers = [1, 5, 800, 3, 7, 9, 15, 27];

myNumbers.sort();

console.log(myNumbers);

 [1, 15, 27, 3, 5, 7, 800, 9] 
//Result Numbers converted to string and then sorted. That's why 800 is before 9. Also 15 and 27 before 3

let myCities = ['New York', 'Washington', 'Chicago', 'Seattle', 'Los Angeles']; //Array of Strings

myCities.sort();

console.log(myCities);

["Chicago", "Los Angeles", "New York", "Seattle", "Washington"] // Result Alphabetically

/******************************************************************************************************************/



Array Map Method

The “map” method for JavaScript array is going to return a new array that meets the conditions set on a function. It works with all types of arrays. Let’s see another brief example about the array map method.

let myNumbers = [1,3,2,6,9];

 let myNumbers1 = myNumbers.map(x => x*2);

 console.log(myNumbers1);


[2, 6, 4, 12, 18] //Result

let myFruits = ['Orange', 'Apple', 'Banana', 'Strawberry', 'Pear']; //String 

let myFruits1 = myFruits.map(x => x.toUpperCase());

console.log(myFruits1);

["ORANGE", "APPLE", "BANANA", "STRAWBERRY", "PEAR"] // Result

/****************************************************************************************************************/

Conclusion

We explained above the most used array methods in JavaScript. Although all examples we showed only the console, we can apply these methods to the DOM. Most times we use these methods while working with JavaScript Frameworks. Frameworks like “Angular”, “Vuejs”, and “Reacts”. In plain JavaScript we can also use them. In a later tutorial we are going to show you how to apply these methods to the DOM. Most of the examples in this tutorial were made using the “Google Chrome Console”. There is also a JavaScript Console Online.

We can find more information about JavaScript Array Methods in the JavaScript MDN. You can find a lot of information there. Thanks, we hoped you learned a lot in this tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *