Useful JavaScript array methods
Tags: javascript, beginners, tutorial, webdev
Published: 2020-06-25 16:52:02

Array is one of the most frequently used data structure in JavaScript. It is an object that can store _a collection of values of the same type_. For example, comments of a blog post or images in a carousel can be stored in an array.

There are a lot of built-in array methods which can help us _add, remove or manipulate data_. This article will cover a number of common array methods, which are grouped by the _purpose_ of data transformation. 

###Table of content
1. Insert - push, unshift
2. Remove - pop, shift
3. Remove/ replace / insert  - splice
4. Slice - slice
5. Merge - concat 
6. Search - includes, find, findIndex, indexOf
7. Reverse - reverse

###Insert - push, unshift 
![Add it to the list](https://media1.tenor.com/images/76f1c74159edcee3a36927396bf8d687/tenor.gif?itemid=14074446)
* push: 
This method can be used when you want to _add one or more items to the end of an array_. The original array will be transformed with the addition of the new item. The method itself will return the new length of the array. 

```javascript
let tea = ['breakfast','lemon','green'];
let count = tea.push('peach');
console.log(tea);
//['breakfast','lemon','green','peach']
console.log(count);
// 4

tea.push('black','strawberry','cranberry');
console.log(tea);
//['breakfast','lemon','green','peach','black','strawberry','cranberry']
```
* unshift:
This method _adds one or more items to the beginning of an array_. Same as 'push', the array in place will be modified and the function itself returns the new length of the array.

```javascript
let letters = ['a', 'b', 'c', 'd', 'e'];
let count = letters.unshift('x', 'y', 'z');
console.log(letters);
//['x', 'y', 'z', 'a', 'b', 'c', 'd', 'e'];
console.log(count);
// 8
```

###Remove - pop, shift
![Cross out](https://media0.giphy.com/media/xT5LMNyVp4kveDqkp2/200.webp?cid=ecf05e47b0afc392db6b5ababbf74d31d09ec0e32d4df01a&rid=200.webp)
* pop:
It _removes the last item from an array_. The original array will be transformed with the removal of the last item. The function itself returns the deleted item.

```javascript
let letters = ['a', 'b', 'c', 'd', 'e'];
let poppedItem = letters.pop();
console.log(letters);
//['a', 'b', 'c', 'd']
console.log(poppedItem);
//'e'
```

* shift: This _removes the first element from an array_. Again, the array in place will be changed and the function returns the deleted element.

```javascript
let letters = ['a', 'b', 'c', 'd', 'e'];
let shiftedItem = letters.shift();
console.log(letters);
//['b','c', 'd', 'e']
console.log(shiftedItem);
//'a'
```
###Remove/ replace / insert - splice

* splice:
This method _modifies the content of an array by removing or replacing existing elements and/or adding new elements_. The original array will be changed.

The syntax would be 
```javascript
let modifiedArray = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
```

Example 1:  at index 0, delete two items "salad" & "steak" 
```javascript
let food = ['salad', 'steak', 'pudding', 'carrot cake'];
food.splice(0,2);
console.log(food); 
//["pudding", "carrot cake"]
```

Example 2: at index 1, delete zero items and insert "snake" and "rabbit"
```javascript
let animals = ["koala", "fish", "tortoise", "whale"]
animals.splice(1,0,"snake","rabbit");
console.log(animals); 
//["koala", "snake", "rabbit", "fish", "tortoise", "whale"]
```

Example 3: at index 0, delete two items "earl grey" & "lemon" and replace them with "breakfast" & "peach"
```javascript
let tea = ["earl grey", "lemon", "green"];
tea.splice(0, 2, "breakfast", "peach");
console.log(tea); 
//["breakfast", "peach", "green"]
```
###Slice - slice
![slice](https://media2.giphy.com/media/10IYOxflm8IbvO/200.webp?cid=ecf05e4725d850523b8470d24739a927d1276dbcd5c7c411&rid=200.webp)
* slice:
This method returns _a desired portion of an array from your specified start point and before your specified end point_. Negative index can be passed in and it will count backwards from the end of an array. 
If the end point is not specified, the rest of the array will be returned. 
If the start point and end point are not specified, it returns a copy of the whole array. 
One thing to note - it _does not modify the original array_ but returns the desired portion. 

```javascript
let food = ['steak', 'pasta', 'cake', 'pudding', 'salad', 'soup'];
let copy = food.slice();
console.log(copy);
//['steak', 'pasta', 'cake', 'pudding', 'salad', 'soup']
let dessert = food.slice(2, 4);
console.log(dessert);
//['cake', 'pudding']
let starter = food.slice(-2); 
console.log(starter);
//['salad', 'soup']
let sweets = food.slice(-4, -2);
console.log(sweets);
//['cake', 'pudding']
```

###Merge - concat 
* concat:
This method is used to _merge two or more arrays_. The original arrays will not be changed. The function itself returns a new array.

```javascript
let tea = ['breakfast','earl grey','green'];
let juice = ['orange', 'pineapple', 'pear'];
let drinks = tea.concat(juice);

console.log(drinks);
//['breakfast','earl grey','green','orange','pineapple', 'pear']

console.log(tea);
//['breakfast','earl grey','green']

console.log(juice);
//['orange', 'pineapple', 'pear']
```
###Search - includes, find, findIndex, indexOf
![Search](https://media1.giphy.com/media/xGdvlOVSWaDvi/200.webp?cid=ecf05e47582d8af395b7ff0fbe0d42f0e84b5b272b4b332f&rid=200.webp)
* includes:
This methods _returns a boolean whether an array contains an element we are looking for_. The second argument, which indicates the index to start searching at, is optional. 

```javascript
let tea = ['breakfast','earl grey','green'];

console.log(tea.includes('breakfast')); 
// true
console.log(tea.includes('strawberry'));
//false
console.log(tea.includes('earl grey', 1));
//true
console.log(tea.includes('earl grey', 2));
//false
```

* find:
If you have a search criteria, you may consider using this method. This returns _the first item which satisfies the criteria specified by you_. If the item cannot be found, _undefined_ is returned. 

In the first example below, the criteria states that the number we look for should be bigger than 3. The search function will return 4 because 4 is the first element in the array that meets the criteria.

In the second example below, the criteria states that the number needs to be smaller than 1. The search function will return undefined because none of the elements in the array meets this criteria. 

```javascript
let numbers = [ 1, 2, 3, 4, 5, 6];
let found = numbers.find(num => num > 3);
console.log(found);
// 4
found = numbers.find(num => num < 1);
console.log(found);
// undefined
```

* findIndex: 
This method is almost the same as _find_. Find returns the first matching item as per the specified criteria, whereas findIndex returns the index of first matching item. 
It returns -1 if no matching item is found.

In the first example below, the criteria states that the number needs to be bigger than 3. The search function will return 1 because 1 is the index of number 4, which is the first number matches the criteria. 

In the second example below, the criteria states that the number needs to be smaller than 2. The search function will return -1 because none of the numbers in the array is smaller than 2. 

```javascript
let numbers = [ 2, 4, 6, 7, 9, 10];
let foundIndex = numbers.findIndex(num => num > 3);
console.log(foundIndex);
// 1
foundIndex = numbers.findIndex(num => num < 2);
console.log(foundIndex);
// -1
```

* indexOf:
This method is almost the same as findIndex, but instead of taking a function as the search criteria and argument, this takes _a value_. 
The second argument, which indicates _the index to start searching at_ , is optional. 

```javascript
let juice = ['orange', 'pineapple', 'pear'];
let index = juice.indexOf('orange');
console.log(index);
// 0
index = juice.indexOf('orange', 1);
console.log(index);
// -1
```

###Reverse - reverse
![reverse](https://media2.giphy.com/media/m4aNskYL5oQqQ/200w.webp?cid=ecf05e476e9a8e32fe9566e15ce4b5ff39bb8a9cb7ad1d69&rid=200w.webp)
* reverse:
This method _reverses an array_ by modifying the original array. 

```javascript
let array = ["Y", "P", "P", "A", "H"];
let reversed = array.reverse();
console.log(reversed);
// ["H", "A", "P", "P", "Y"]
```
Thank you for reading this article! This article is far from comprehensive. There are still many methods which have not been covered. If you want to find out more about JS array methods, you can check out the docs on [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array). It's really good reference for learning and understanding how they work. 

<a href="https://www.buymeacoffee.com/phyllisyymo" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>