JavaScipt: Everything you need to know about arrays.
Tags: webdev, programming, tutorial, javascript
Published: 2023-08-21 19:26:45

Arrays are superheroes when it comes to organizing data. This article explains how they function, why they're essential for anyone looking to properly manage data and how to effectively manipulate it.

Overview :
1. [What is an array?](#array)
2. [Initializing an array](#create)
    - [Array literal](#literal)
    - [New keyword](#new)
3. [length property](#len)
4. [Accessing and changing array elements](#change)
5. [Multi-dimensional array](#multi)
6. [Array Methods](#methods)
    - [Add methods](#add)
    - [Remove methods](#remove)
    - [Transform methods](#transform)
    - [Search methods](#search)
    - [Conversion methods](#convert)
    - [Copy methods](#copy)


## <a id="array">What is an array?</a>
Think of an array as a multi-drawer cabinet. Each drawer in that cabinet has a different item in it. You can reach an item by simply opening the drawer that has the item you want.

Similarly an array is a variable that can store multiple values.

## <a id="create">Initializing an array</a>
We've previously seen how to Initialize a variable.
```javascript
let name = "John";
```

### <a id="literal">Array literal</a>
Initializing an array is similar to initializing a variable with some differences. While a variable can store a single data type as we've seen in the example above, an array can hold multiple values of different data types. You declare an array using square brackets.
```javascript
const food = [];
```
You can pass multiple values of different data types to the square brackets to initialize the array.

```javascript
const values = ["ice cream", 57, "biscuit", true, 3.14];
```
### <a id="new"> New Keyword </a>
You can also declare and assign values to an array using the `new` keyword.
```javascript
const values = new Array();
const elements = new Array("one", 2, true, 3.14);
```
These two methods do exactly the same thing, but use the array literal method for efficiency, readability, and speed.

## <a id="len">Length Property</a>
In the previous article <a href="https://dev.to/fullstackjo/javascript-how-to-make-the-most-out-of-strings--255i"> How to make the most out of strings</a> We've seen what the `length` property does. Let's go over it one more time.
The length property returns the size of the array or the number of items in the array.
```javascript
const values = ["ice cream", 57, "biscuit", true, 3.14];
console.log(values.length); //5
```
## <a id="change"> Accessing and changing array elements </a>
The position of an item in an array is known as an index. We start counting the items of an array from zero. This is known as zero-based indexing.

```javascript
const values = ["ice cream", 57, "biscuit", true, 3.14];
let index0 = values[0];
console.log(index0); //ice cream
```

Let's change an item in the `values` array
```javascript
const values = ["ice cream", 57, "biscuit", true, 3.14];
values[1] = 26;
console.log(values);
//[ 'ice cream', 26, 'biscuit', true, 3.14 ]
```
As we can see the number 57 was modified to 26. 

_The length property always starts counting from 1. It's always 1 number higher than than the index_
You can access array elements using the length property. For example, let's access the last item and second to last item of the `values` array.
```javascript
const values = ["ice cream", 57, "biscuit", true, 3.14];

console.log(values[values.length-1]); //3.14
console.log(values[values.length-2]); //true
```
So what's happening in the example? Let's break it down.
We've previously accessed the first element of the array using this notation `values[0]` which gave us `ice cream`. 
`values[values.length-1]` here is `values[5 - 1]` which is `value[4]` which will give us `3.14`. 
**Why are we using `-1`?**
As we've previously stated arrays use zero-based indexing. if we try to get the value at `value[5]` we will get `undefined` which means that there's no value assigned to the index 5 since we start counting from zero. Counting from `0` to `4` gives us five values which is the length of the array.

```javascript
const values = ["ice cream", 57, "biscuit", true, 3.14];

console.log(values[values.length]); //undeifned
```

## <a id="multi">Multi-dimensional array</a>
Now that we have a strong understanding of what an array is, let's explain what a multi-dimensional array is. 

A multi-dimensional array is an array that contains other arrays.

```javascript
const multiDimensional = [
  [2, "cat", false],
  [3.14, true, "mango"],
  ["peach", 32, true]
];
```
Multi-dimensional arrays can be accessed in the same way as an array by using bracket notation. Take our `multiDimensional` array which has `1 outer layer` which is the entire array. 
```javascript
const multiDimensional = [
  [2, "cat", false],
  [3.14, true, "mango"],
  ["peach", 32, true]
];

console.log(multiDimensional[0]); //[2, "cat", false]
console.log(multiDimensional[1]); //[3.14, true, "mango"]
console.log(multiDimensional[2]); //["peach", 32, true]
```
The `inner layer` consists of `3 inner layers` which are the 3 arrays. The items (values) within each inner array belong to the inner layer.

Let's say we want to access the value `mango` in our example:
```javascript
const multiDimensional = [
  [2, "cat", false],
  [3.14, true, "mango"],
  ["peach", 32, true]
];

console.log(multiDimensional[1][2]);//mango
```
Our value `mango` is the second array in `multiDimensional`, so it's in position 1 (_remember zero-based indexing_). The `mango` value is the last item in that array meaning at position 2.

## <a id="methods">Array methods</a>
Array operations like insertion, deletion, searching, and transformation can be performed on an array's elements using array methods. These methods make writing custom code less difficult and create more readable, compact and useful code.

| Method                | Description                                                           |
|-----------------------|-----------------------------------------------------------------------|
| `push()`              | Adds one or more elements to the end of an array.                     |
| `unshift()`           | Adds one or more elements to the beginning of an array.               |
| `splice()`            | Adds or removes elements from an array at a specified index.          |
| `pop()`               | Removes the last element from the end of an array and returns it.     |
| `shift()`             | Removes the first element from the beginning of an array and returns it. |
| `map()`               | Creates a new array by applying a function to each element of the array. |
| `filter()`            | Creates a new array with elements that pass a certain condition.      |
| `reverse()`           | Reverses the order of elements in an array.                           |
| `sort()`              | Sorts the elements of an array in place or based on a provided function. |
| `copyWithin()`        | Copies elements within an array to a specified destination.           |
| `indexOf()`           | Returns the first index at which a given element can be found in the array. |
| `lastIndexOf()`       | Returns the last index at which a given element can be found in the array. |
| `includes()`          | Checks if an array includes a certain element, returning a boolean.   |
| `find()`              | Returns the first element in the array that satisfies a given condition. |
| `findIndex()`         | Returns the index of the first element that satisfies a given condition. |
| `join()`              | Joins all elements of an array into a string using a specified separator. |
| `toString()`          | Converts an array to a string representation.                          |
| `concat()`            | Combines two or more arrays, returning a new concatenated array.      |
| Spread Operator (`...`) | Expands an array into individual elements.                            |
| `slice()`             | Returns a shallow copy of a portion of an array into a new array.     |
| `reduce()`            | Applies a function against an accumulator and each element in the array, reducing it to a single value. |


### <a id="add">Add methods</a>

We can add an element to an array using multiple methods.
- Using indexing
```javascript
const values = [2, "cat", false]

values[3] ="miami";
console.log(values); //[2, "cat", false, "miami"]
```
- Using length property
```javascript
const values = [2, "cat", false]

values[values.length] ="miami";
console.log(values); //[2, "cat", false, "miami"]
```
Using these methods is not recommended because it can create undefined "holes" in an array.
```javascript
const values = [];
values[2] = 'Hello';

console.log(values);        // Output: [ , , 'Hello' ]
console.log(values.length); // Output: 3
console.log(values[0]);     // Output: undefined
console.log(values[1]);     // Output: undefined
console.log(values[2]);     // Output: 'Hello'
```
| Category             | Array Methods                                       |
|----------------------|-----------------------------------------------------|
| Element Insertion    | `push()`, `unshift()`, `splice()`       |

- push() 

The `push()` method alters the array by adding a single or more values to the end of it and returns the new `length` of the altered array.

```javascript
const numbers = [1, 2, 3];
const newLength = numbers.push(4, 5);

console.log(numbers);    // Output: [1, 2, 3, 4, 5]
console.log(newLength);  // Output: 5
```

- unshift()

The `unshift()` method is used to add a single or multiple values to the beginning of the array and returns its new `length`.

```javascript
const numbers = [3, 4, 5];
const newLength = numbers.unshift(1, 2);

console.log(numbers);    // Output: [1, 2, 3, 4, 5]
console.log(newLength);  // Output: 5
```
- splice() 

The `splice()` method is used to add remove or replace values at a specified index.
Here's an example of using splice to add and remove elements: 
```javascript
const fruits = ['apple', 'banana', 'orange', 'grape'];
const removedFruits = fruits.splice(1, 2, 'melon', 'cherry');

console.log(fruits);          
// Output: ['apple', 'melon', 'cherry', 'grape']
console.log(removedFruits);    
// Output: ['banana', 'orange'] (removed elements)
```
## <a id="remove">Remove methods</a>
| Category             | Array Methods                                       |
|----------------------|-----------------------------------------------------|
| Element Deletion     | `pop()`, `shift()`, `splice()`                      |

- delete() 

```javascript
const values = ["apple", true, 2, "Mango"];
delete values[1];
console.log(values); //['apple', <1 empty item>, 2, 'Mango']
console.log(values.length);//4
```
It is not recommended to remove an item from an array using the `delete()` method because the original array length remains unchanged because it only removes the value from the array without freeing up that index. Meaning the length of the array stays the same.

- pop()

The `pop()` method alters the array by removing the last element from the array and returns the removed value.

```javascript
const numbers = [1, 2, 3, 4, 5];
const removedElement = numbers.pop();

console.log(numbers);         // Output: [1, 2, 3, 4]
console.log(removedElement);  // Output: 5 (last element)
```
- shift() 

The `shift()` method alters the array by removing the first element of it and returns the removed value.
```javascript
const fruits = ['apple', 'banana', 'orange', 'grape'];
const removedFruit = fruits.shift();

console.log(fruits);         // Output: ['banana', 'orange', 'grape']
console.log(removedFruit);   // Output: 'apple' (first element)
```
## <a id="transform">Transform methods</a>
| Category             | Array Methods                                       |
|----------------------|-----------------------------------------------------|
| Element Transformation| `map()`, `filter()`, `reverse()`, `reduce()`,`sort()`, `copyWithin()` |

The `map()`, `filter()`, and `reduce()` methods are `higher order functions` which we'll discuss in an upcoming article. All you have to know for now is that they're array methods do not modify the original array but return a new modified array. 

- reverse() 

The `reverse()` method alters the original array and reverses the order of its values.

```javascript
const numbers = [1, 2, 3, 4, 5];
numbers.reverse();

console.log(numbers);  // Output: [5, 4, 3, 2, 1] (original array is reversed)
```
- sort()

The `sort()` method alters the original array and sorts its values in ascending order.

```javascript
const fruits = ['banana', 'apple', 'grape', 'orange'];
fruits.sort();

console.log(fruits);  // Output: ['apple', 'banana', 'grape', 'orange'] (sorted alphabetically)

//sorting numbers
const numbers = [4, 2, 8, 6, 1];
numbers.sort((a, b) => a - b);

console.log(numbers);  // Output: [1, 2, 4, 6, 8] (sorted numerically)
```
When sorting numbers in ascending order, the expression `a - b` is frequently used as a comparison function. This method makes use of the sort() method's behavior, which assumes the comparison function that returns a negative, zero, or positive value to determine the order of elements.
**Why ` a - b ` ?**

1. If `a - b` returns `a` negative value, it indicates that `a` should come before `b` in the sorted order.
2. If `a - b` returns zero, it indicates that `a` and b are considered equal in terms of sorting order.
3. If `a - b` returns `a` positive value, it indicates that `a` should come after `b` in the sorted order.


- copyWithin() 

The `copyWithin()` method does not modify the array and copies a piece of it to another place in the array.
it takes 3 parameters: 
- `target`: which is where the elements you're copying will be placed.
- `start`: which is from where this method will start copying the elements in the array.
- `end`: Which is the index prior to which copies of elements should stop. It takes the array's length as a default if omitted.

```javascript
const numbers = [1, 2, 3, 4, 5];
numbers.copyWithin(0, 3, 5);

console.log(numbers);  // Output: [4, 5, 3, 4, 5]
```

## <a id="search">Search methods</a>
| Category             | Array Methods                                       |
|----------------------|-----------------------------------------------------|
| Element Search       | `indexOf()`, `lastIndexOf()`, `includes()`, `find()`, `findIndex()` |

- indexOf()

The `indexOf()` method returns the index of the element you're trying to find and `-1` if it was not found.

```javascript
const fruits = ['apple', 'banana', 'orange', 'apple'];
const index = fruits.indexOf('apple');

console.log(index);  // Output: 0 (index of the first 'apple')
```

- lastIndexOf()

The `lastIndexOf()` method returns the index of last occurrence of the element you're trying to find and `-1` if it was not found.

```javascript
const fruits = ['apple', 'banana', 'orange', 'apple'];
const lastIndex = fruits.lastIndexOf('apple');

console.log(lastIndex);  // Output: 3 (index of the last 'apple')
```
- includes()

The `includes()` method indicates if an element is present in an array. It returns `true` if the element is in the array and `false` if it is not.

```javascript
const fruits = ['apple', 'banana', 'orange'];
const hasBanana = fruits.includes('banana');

console.log(hasBanana);  // Output: true (array includes 'banana')
```
_find and findIndex methods are both higher order functions which we will discuss in a later article._

### <a id="convert">Conversion methods</a>
| Category             | Array Methods                                       |
|----------------------|-----------------------------------------------------|
| Element Conversion   | `join()`, `toString()`                              |

- join()

The `join()` method creates a string using the argument passed as a separator.
```javascript
const fruits = ['apple', 'banana', 'orange'];
const joinedString = fruits.join(', ');

console.log(joinedString);  // Output: "apple, banana, orange"
```
- toString()

The `toString()` method converts the array into a string separated by comas.
```javascript
const numbers = [1, 2, 3, 4, 5];
const numbersString = numbers.toString();

console.log(numbersString);  // Output: "1,2,3,4,5"
```

### <a id="copy">Copy methods</a>
| Category             | Array Methods                                       |
|----------------------|-----------------------------------------------------|
| Copying              | `concat()`, Spread Operator (`...`), `slice()`      |

- concat() 

The `concat()` method joins two or more arrays together and returns a new array.
```javascript
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combinedArray = array1.concat(array2);

console.log(combinedArray);  // Output: [1, 2, 3, 4, 5, 6]
```

- The spread operator `(...)`

This operator is used to expand element of an array and can be used to combine arrays.

```javascript
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combinedArray = [...array1, ...array2];

console.log(combinedArray);  // Output: [1, 2, 3, 4, 5, 6]
```
- slice()

The `slice()` method is used to create a copy of a portion of an array and returns a new array. 
```javascript
const numbers = [1, 2, 3, 4, 5];
const copiedNumbers = numbers.slice(1, 4);

console.log(copiedNumbers);  // Output: [2, 3, 4]
```