Arrays?
Tags: javascript, beginners
Published: 2022-08-07 18:11:00

In the beginning of your journey learning Javascript, arrays can be quite confusing. There are **SO MANY** different methods that can be used on them. I know I had trouble when I first started learning. So, let's start in the beginning.

##What is an array?
An array is a data structure that holds, well data. It can be **strings** or other **data structures**. 

```javascript
const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries'
]

```
This is an example of a simple array. This is an array of **strings**.

```javascript
const myFruit = [
'apples',['oranges',['bananas'], 'pineapple'],'strawberries'
]

```
While this one still uses strings you can see that there are **arrays** embedded in myFruit.

```javascript
const favoriteFruits = [
{name: 'Joe',
favoriteFruit: 'apples'},
{name: 'Susan',
favoriteFruit: 'bananas'},
{name: 'Steve',
favoriteFruit: 'pineapple'},
{name: 'Betty',
favoriteFruit: 'kiwi'}
]
```
Here we have an array with nested **objects**. In my time of learning javascript, this has been the most common form of an array that I have seen.

This sums up what an array is. It can be simple like a few strings or it can have a nested data structure. Next I will talk about different ways to modify the arrays. 

#Destructive vs. Nondestructive
Before we get into modifying arrays, we need to talk about **destructive** vs. **nondestructive**. 

##Destructive 
**Destructive** refers to idea that you are modifying the original array. There are a few methods that I talk about that are going to be referred to as a **destructive** method. 

##Nondestructive

Well, if you assume that **nondestructive** is the opposite of destructive, then you're CORRECT!! When you use a **nondestructive** method then you are creating a new array from the original. It's like you have a bag of m&m's and run them threw a machine to pick out the blue and yellow ones to make a new bag. These are the usual preferred methods to use on arrays.

#Array Methods

Welcome to the world of modifying arrays! Let's start with the **destructive** methods.

##Destructive

Here's a list of the **destructive** methods:
- `.push()`
- `.unshift()`
- `.pop()`
- `.shift()`
- `.splice()`

`.push()` and `.unshift()` both add elements to the original array, while `.pop()` and `.shift()` both remove elements from the original array. 

### .push()

```javascript
const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries'];
myFruit.push('pineapple');
myFruit // =>['apples', 'oranges', 'bananas', 'strawberries', 'pineapple']

```
Here you can see that we used `.push()` to **'push'** pineapple into the original array. `.push()` will add the passed in element to the end of the array. Which keeps it the same array, but adds a new element into the original. 

### .unshift()

```javascript
const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries'];
myFruit.unshift('kiwi');
myFruit // =>['kiwi','apples', 'oranges', 'bananas', 'strawberries']
```
Going back to my original array myFruit, you can see I used `.unshift()` to add in kiwi. `.unshift()` will add the new element to the beginning of the original array. Which destructively changes the original array.

### .pop()

```javascript
const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries'];
myFruit.pop();
myFruit //=> ['apples', 'oranges', 'bananas']
```

Back to my original array, `.pop()` removes the last element of the array. So you can see we no longer have strawberries in the original array. Notice that I don't pass in argument. This is because you can't select what element you are trying to remove. `.pop()` only removes the last element of the array.

### .shift()

```javascript
const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries'];
myFruit.shift();
myFruit //=> ['oranges', 'bananas', 'strawberries']
```
Once again you can see that there is no argument that is being passed through `.shift()`, but it did remove apples. `.shift()` removes the first element of your original array.

### .splice()

```javascript
const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries'];
myFruit.splice(2, 1, 'pineapple');
myFruit; // => ['apples', 'oranges', 'pineapple', 'strawberries']
```
 `.splice()` has a few different ways you can use it. In the example above I used the `.splice()` operator to remove bananas from my string and insert pineapple in its place. Well, how does it know thats what I wanted? Let's break down the arguments I passed through. The first argument is 2, so that means that the operator starts at that point. That selected bananas. Next, we have 1 which means that it's going to remove one element. Think of it as you've highlighted the starting point and now you're going to delete it and replace it with something new. Next is pineapple, which is the new element thats added into the place of the element you removed. `.splice()` allows you to more specifically alter the original array. You can choose to add a new element anywhere in the array. You don't have to delete any elements in order to pass in a new element. What does that look like?  Let's take the prior example and see.

```javascript
const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries'];
myFruit.splice(2, 0, 'pineapple');
myFruit; // => ['apples', 'oranges', 'pineapple', 'bananas', 'strawberries']
```
 You can see by passing in a 0 at the second argument, it doesn't remove any of the element it just simply adds the third argument into the array. So now you've seen how you can use `.splice()` more than 1 way. 

## Nondestructive

Here is a list of **nondestructive** methods:
- `.slice()`
- Spread Operator

### .slice()

```javascript
const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries'];
myFruit.slice(0,2);
// => ['apples', 'oranges', 'bananas']
myFruit;
//=> ['apples', 'oranges', 'bananas', 'strawberries']
```
`.slice()` is a great way to select a certain part of your original array and make it into a new array. Above you can see that the first argument that I passed in was the starting point for the new array. The second argument is the last element I wanted to be grabbed from the original array, so the new array was made up of `['apples', 'oranges', 'bananas']`.

### Spread Operator

```javascript
const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries'];
const copyMyFruit = ['pineapple', ...myFruit];
copyMyFruit;
// => ['pineapple', 'apples', 'oranges', 'bananas', 'strawberries']
```
The spread operator allows you to create a new array and add a new element to that array. Above you can see that I added `pineapple` to a copy of the original array because `pineapple` was in front of the array it added it to the beginning, but you can also add the element to end by switching the two. You can also add multiple elements when using the spread operator.

#Array Iterators

## What are array iterators? 
Here is a list of the more common used array iterators:
- `.forEach()`
- `.map()`
- `.filter()`
- `.find()`
- `.reduce()`
- `.some()`
- `.every()`

Array iterators are different operators that are used on arrays. They each have their own purpose. Some create new arrays, some just help reach different parts of arrays. These are all nondestructive methods to use on arrays.

### .forEach()

```javascript
const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries'];
myFruit.forEach(function(myFruit){
console.log(`Can I have some ${myFruit}, please?`)}
//Can I have some apples, please?
//Can I have some oranges, please?
//Can I have some bananas, please?
//Can I have some strawberries, please?
```
`.forEach()` loops through the array and will plug in each element to what it's being passed through. Above you can see that I `console.log()` a string and interpolated the array into it, which gave us the strings that used only one element from the original array.

### .map()

```javascript
const myNumbers =[ 45, 15, 12, 11];
myNumbers.map(function(num){
return num * 5 });
// [225, 75, 60, 55]
```
`.map()` returns a new array after the original array is run through the callback function. Above you can see that the function is multiplying each element of the array by five and returning the new array.

### .filter()

```javascript
const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries'];
myFruit.filter(function (fruit){
    return fruit[3] === 'a'});
//['bananas', 'strawberries']
```
`.filter()` returns a new array that past the test of the function that the original array is being run through. The example above shows the test of checking for what fruits third character is `a`. You can see that only `'bananas', 'strawberries'` past the test and are generator into a new array. 


### .find()

```javascript
const myNumbers =[ 45, 15, 12, 11];
myNumbers.find(function (num) {
    return num < 13 });
// 12
```
`.find()` allows you to pass the array into a function that has a set parameter for what element you are looking for. Above you can see that the parameter I gave was looking for an element that was less than 13. It ran each element through and returned the first element that met that parameter. 

### .reduce()

```javascript
const myNumbers =[ 45, 15, 12, 11];
myNumbers.reduce((previousValue, currentValue) => previousValue + currentValue, 10)
//93
```
`.reduce()` reduces the array down to one sum. Above I passed in the previous value and starting at 0 there is no number prior, so I set 10 as the base number. Which then the function continues to add each element to the overall total giving us the output of 93.

### .some()

```javascript
const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries']
myFruit.some(fruit => fruit.length > 4);
//true
```
`.some()` returns true or false based off the individual elements in the array. You can see above that we are testing in the elements length is greater than four. Because `apples` length is greater than 4 it returns true. 

### .every()

```javascript
const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries']
myFruit.every(fruit => fruit.length > 6);
//false
```
`.every()` returns true or false if the whole array passes the test thats its being passed through. Above you can see that we passed the array in checking if each elements length was longer than six characters. Because `apples` does not past the test it returns a negative. 

This is a brief overview of array methods. If you interested in reading more check out the docs here [Array MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array).