6 Array methods every JavaScript developer must know
Tags: javascript, webdev, beginners, programming
Published: 2023-01-04 03:30:00

An array in JavaScript is an ordered collection of data that can hold multiple values of the same or different types. It is a data structure that is used to store a collection of items in a single place.

Arrays are created using the **`Array`** constructor or the square brackets (**`[]`**) notation. For example:

```jsx
// Using the Array constructor
const arr1 = new Array("🍇","🍈","🍉","🍋","🍌");

// Using square brackets
const arr2 = ["🍇","🍈","🍉","🍋","🍌"];
```

You can access the items in an array using their indices, which are the positions of the items in the array. For example, to access the second item in the **`arr2`** array, you can use the following syntax:

```jsx
console.log(arr2[1]);  // Output: 🍈
```

You can also modify the values in an array by assigning new values to the indices. For example:

```
arr2[1] = "🍍";  // The second item in the array is now 🍍
```

Arrays in JavaScript are zero-indexed, meaning that the first item in the array is at index 0, the second item is at index 1, and so on.

In addition to storing simple values, arrays can also store complex data types, such as objects or other arrays.

```
const arr3 = [1, 'hello', [1, 2, 3], {key: 'value'}];
```

There are many methods available for working with arrays in JavaScript, such as **`push`** to add items to the end of an array, **`unshift`** to add items to the beginning of an array and **`splice`** to insert or remove items from an array. I will explain some of the important methods of the JavaScript array. 

# Insert ****Elements to a JavaScript array - array.push()****

There is a `push` method to add elements to the JavaScript array. `push()` method is actually a method function that receives an argument as an array element. It always adds elements to the end of the array. Another method to perform the same operation using `unshift` add elements to the start of the array. 

```jsx
const winterFruits = [],
// winter has come, now where is the fruit basket, let's fill it

winterFruits.push("🍊")
winterFruits.push("🥕")
winterFruits.push("🍍")

// print
console.log(winterFruits)   // ['🍊', '🥕', '🍍']
```

# ****Remove Elements from an Array in JS****

There is a `pop` method to remove elements from the JavaScript array. the `pop()` method  actually a method function, available on the array. It always removes elements one by one from the end of an existing array. Another method to perform the same operation using `shift` add elements to the start of the array. `pop` returns removed element.

Let’s do eat a burger,

```jsx
const burgers = ['zinger stack 🍔', 'stack 🍔', 'mighty burger 🍔']

// try mighty bites, so remove it.
burgers.pop() // so here is your: 'mighty burger 🍔'

// how about other burgers eat one, for 
console.log(burgers)

// I will like you to try zinger stack. I insist 
burgers.shift() // how was it? 'zinger stack 🍔' 
```

# Modify the JS array by adding, removing, and replacing, elements

There is a `splice` method to add, remove, replacing, elements at a specific index. It modifies the array in place and does not create a new array. `splice()` is a JavaScript method function, that allows passing 3 main arguments with one optional. 

 

**Read more about splice arguments**

[Array.prototype.splice() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice)

## Remove elements from the array using splice

The major use of the `splice()` method is to delete elements from an array. It returns an array of the elements deleted and modifies the original array. 

```jsx
const array = ['porsche 911 ', 'TNT 150I', 'a large house', 'disney plus', 'deezer hifi'];
//array.splice(startIndex, how many elements should be removed)

// choose a number from 0 to 4
const candidateResponse = array.splice(2, 1); // removes elements at index 2 ('a large house') from the array and returns them

console.log(array); // Output: ['porsche 911 ', 'TNT 150I', 'disney plus', 'deezer hifi']
console.log(candidateResponse); // Output: ['a large house'] 

// candidate won a large beautiful house. good one, try yours. 
```

## Add elements to an array using splice

The splice method can also be used to add elements to an array at a specific index. Let’s see how

```jsx
let tasks = ['Take out the trash', 'Do the dishes', 'Mow the lawn'];

tasks.splice(0, 0, 'Buy groceries'); // adds the new task at index 0, without removing any elements

console.log(tasks); // Output: ['Buy groceries', 'Take out the trash', 'Do the dishes', 'Mow the lawn']
```

**Practical example** 

```jsx
let items = ["apple", "banana", "cherry"];

// Get the new item from the input field
let newItem = document.getElementById("new-item-input").value;

// Add the new item to the list
items.splice(items.length, 0, newItem);

// Update the display to show the new list
updateListDisplay(items);
```

**Note:** It always elements after a specific index.

## Replace elements in an array using splice

The splice method can replace elements in an array. It removes elements and adds elements at a specific index.  

```jsx
// syntax
array.splice(startIndex, deleteCount, element1, element2, ...);
```

```jsx
let array = [1, 2, 3, 4, 5];

let removed = array.splice(2, 2, 6, 7); // removes elements at index 2 and 3 (3 and 4) and replaces them with 6 and 7

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

# Sort elements of the JavaScript array

The **`sort`** method is a built-in JavaScript function that allows you to sort the elements of an array in place. It modifies the original array and does not create a new array.

Here is an example of how to use the **`sort`** method to sort the elements of an array in ascending order:

```jsx
let array = [3, 5, 1, 2, 4];

array.sort(); // sorts the array in ascending order

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

## Sorting products using JavaScript

Why not take a sneak peek at a real-world scenario? 

```jsx
let products = [
  { name: "Product A", price: 50 },
  { name: "Product B", price: 20 },
  { name: "Product C", price: 30 },
  { name: "Product D", price: 10 },
];

products.sort((a, b) => {
  return a.price - b.price;
});

console.log(products);
// Output:
// [
//   { name: "Product D", price: 10 },
//   { name: "Product B", price: 20 },
//   { name: "Product C", price: 30 },
//   { name: "Product A", price: 50 }
// ]
I;
```

Another way to do sorting is using a sort algorithm. Explained here. 

# How to reverse an array in JavaScript

To reverse an array in JavaScript, you can use the **`reverse`** method provided by the Array object. The **`reverse`** method modifies the original array in place and does not create a new array.

```jsx
let array = [1, 2, 3, 4, 5];

array.reverse();

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

# Closing remarks

You have just learned about the 3 to 4 methods of the JavaScript array. The array is a widely used data structure in building frontend and backend apps. When an array is used to store large, complex data, methods are required to deal with data to sort, remove, and add new data. So array is overall very useful and easy to understand with a bunch of problem-solving solutions.