10 Array Methods You Should Know 👀
Tags: javascript, beginners, codenewbie, webdev
Published: 2020-01-28 18:39:31

<h1>The Basics 🕺</h1>
So what _are_ arrays? 🤔
<blockquote>
<b>ar·ray</b>
/əˈrā/
noun
1. an ordered series or arrangement.
</blockquote>

<blockquote>
In computer science, an array data structure, or simply an array, is a data structure consisting of a collection of elements, each identified by at least one array index or key. An array is stored such that the position of each element can be computed from its index tuple by a mathematical formula.
</blockquote>


In JavaScript, arrays are basically a data structure that holds a list of values. These values can be strings, integers, or even objects. Arrays don't have fixed types or restricted lengths.

Arrays are referenced using square brackets: <code>[]</code> The **index** of an element simply means the "location" of the element in the array. You count the index of an element by starting at 0 rather than 1. For example, <code>newArray = [1, 2, 3, 4];</code>. In this case, 1 is in the 0th place. 

You can retrieve an item by using its index with brackets <code>[]</code>. For example: <code> newArray[0]</code> That will return <code>1</code>. <code> newArray[2]</code> will return <code>3</code>. 
Another example would be <code>let cats = ["Sebastian", "Emmy", "Mr.Whiskers"]; cats[1]</code> would return <code>"Emmy"</code>


If you know those basic concepts, you can begin to learn array methods. You'll quickly find that there are a variety of different methods out there can make your logic streamlined and efficient. Here are 10 commonly used methods to master. 🆒

<h2>Methods 🥳</h2>

**1) .push()** | adds an element to the _end_ of an array

```javascript
       let names = ["Nick", "Chris", "Ben"];
       names.push("Rebecca"); 
       console.log(names);
       // names = ["Nick", "Chris", "Ben", "Rebecca]; 
```

  **2) .pop** | removes the _last_ element in an array

```javascript
       let cities = ["New York", "Los Angeles", "Atlanta"]; 
       cities.pop(); 
       console.log(cities); 
       // cities = ["New York", "Los Angeles"];
```

  **3) .shift** | removes the _first_ element an array

```javascript
       let ages = [30, 26, 24, 20];
       ages.shift(); 
       console.log(ages);
       // ages = [26, 24, 20]
```

  **4) .unshift** | adds an element to the _beginning_ of an array

```javascript
       let ages = [30, 26, 24, 20];
       ages.unshift(60); 
       console.log(ages);
       // ages = [60, 30, 26, 24, 20];
```

  **5) .splice** | adds, removes, or replaces an element at a given index. The first parameter is the index, the second parameter is how many elements you want to remove, and the 3rd parameter is the value you want to replace or add. 

```javascript
       // to remove elements
       let animals = ["cat", "dog", "shark", "horse", "alligator"]; 
       animals.splice(1, 2); 
       // remove 2 elements at index 1, including index 1
       // so what's being "spliced" is "dog" and "shark"
       console.log(animals);
       // animals  = ["cat", "horse", "alligator"];
```
```javascript
       // to add elements
       let animals = ["cat", "dog", "shark", "horse", "alligator"]; 
       animals.splice(2, 0, "zebra"); 
       // at index 2, splice (or remove) 0 elements, add "zebra" 
       animals  = ["cat", "dog", "zebra", "shark", "horse", "alligator"]; 
```
```javascript
       // to replace elements
       let animals = ["cat", "dog", "shark", "horse", "alligator"]; 
       animals.splice(2, 1, "zebra"); 
       // an index 2, replace 1 element ("shark") with "zebra"
       // at index 2, splice (or remove) 0 elements, add "zebra" 
       animals  = ["cat", "dog", "zebra", "horse", "alligator"]; 
```

  **6) .slice** | returns a shallow copy of an array. It can take one or two parameters that represent the "beginning" and "end" of where you want to slice. Note that the "beginning" parameter is included whereas the "end" parameter should not be included.

```javascript
       let colors = ["Blue", "Red", "Orange", "Purple", "Pink"];
       let lessColors = colors.slice(1, 3);
       console.log(lessColors); 
       // colors = ["Red", "Orange"];
```
👉 If you only include one parameter, it'll keep every element after the "beginning" value. 

```javascript
       let colors = ["Blue", "Red", "Orange", "Purple", "Pink"];
       let lessColors = colors.slice(2); 
       // colors[2] = "Orange" which now becomes the 1st element
       console.log(lessColors);
       // lessColors = ["Orange", "Purple", "Pink];
```

❗️ .splice vs .slice can be hard to remember. Think of splice as a very dynamic method with the ability to remove, replace, or add elements and modifies the existing array... whereas slice mainly removes values and creates a new array.

  **7) .forEach** | performs a function for each element in an array

```javascript
       let miles = [1, 3, 5, 10];
       let moreMiles = [];
       miles.forEach(element => moreMiles.push(element + 10))
       console.log(moreMiles);
       // [11, 13, 15, 20];
```

  **8) .map** | creates a new array with the result of executing the provided function to each element in the array

```javascript
       let population = [200, 600, 170, 100];
       let doublePopulation = population.map(element => element * 2);
       // we are assigning the result of mapping to doublePopulation
       // we would not be able to do this with the .forEach method
       // because it returns undefined
       console.log(doublePopulation);       
       // [400, 1200, 340, 200]
```

❗️ Note that the difference between .forEach and .map is that when you call the .forEach method, it returns undefined and .map returns a new array! 

  **9) .reduce** | combines (or reduces) the array into one single value. A simple way to learn the reduce method is to add together all elements in an array. The method takes two parameters, the accumulator and the current value.

```javascript
       let ticketPrices = [99.54, 56.43, 122.94];
       let totalCostOfTickets = ticketPrices.reduce((total, amount) => total + amount)
       // the accumulator is total; it's holding the new values as you add
      // the amount is the next ticket price. 
       totalCostOfTickets = 278.91

```

  **10) .filter** | creates a new array with the elements that pass the provided function. 

```javascript
       let names = ["Rebecca", "Chris", "Ben", "Rachel"];
       names = names.filter(name => name[0] === "R") 
       // this is looping through each name and checking if 
       // the first index of the string (aka first letter) is "R".
       console.log(names):
       // names = ["Rebecca", "Rachel"];
```

```javascript
       let ages = [16, 21, 26, 14];
       ages = ages.filter(age => age >= 21) 
       // this is looping through each age and checking if  
       // the value is greater than or equal to 21.
       console.log(ages):
       // ages = [21, 26];
```

-----------------------------------------------------------------

There are many <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" target="_blank"> more methods </a> out there, but these are super helpful to keep in your tool belt! 🙌 Thanks for reading, and feel free to reach out if you have any feedback on this article or any questions!