skip to content
Dev Journal

Mastering Array Methods

/ 2 min read

You need to know how to do three things with arrays:

  1. Find the position of an item
  2. Add an item to the array
  3. Remove an item from the array

As you go through this lesson, you’ll see various ways to do these tasks in JavaScript. They are all correct. Over time, you’ll learn to choose the methods you prefer. For now, focus on understanding how each method works.

Finding the Position of an item

To locate a primitive value in an array, use indexOf. It returns the index of the item if found, otherwise, it returns -1.

const fruitBasket = ["apple", "banana", "orange", "pear"]
const posOfBanana = fruitBasket.indexof("banana") // 1
const posOfKiwi = fruitBasket.indexOf("kiwi") // -1

For objects, arrays, or functions use findIndex

Adding Items to an Array

You can add items to the start, end, or middle of an array. Let’s start with the beginning and end.

Start: Use unshift to add items to the start

const array = [3, 4, 5]
array.unshift(2)
console.log(array) // [2, 3, 4, 5]

End: Use push to add items to the end

const array = [3, 4, 5]
array.push(6)
console.log(array) // [3, 4, 5, 6]

Removing Items from an Array

You can remove items from the start, end, or middle of an array. Let’s start with the beginning and end.

Start: Use shift to remove items from the start

const array = [3, 4, 5]
const itemOne = array.shift()
console.log(itemOne) // 3
console.log(array) // [4, 5]

End: Use pop to remove items from the end

const array = [3, 4, 5]
const lastItem = array.pop()
console.log(array) // [3, 4]
console.log(lastItem) // 5

The Almighty splice Method

splice lets you add or remove items from any position in an array. The syntax is:

const deletedItems = array.splice(index, deleteCount, itemsToAdd)
  • index: Where to start modifying the array.
  • deleteCount: Number of items to delete.
  • itemsToAdd: Items to add.

Add Items:

const array = [3, 4, 5]
array.splice(0, 0, 1, 2);
console.log(array) // [1, 2, 3, 4, 5]

Remove Items:

const array = [3, 4, 5]
const deleted = array.splice(0, 2)
console.log(array) // [5]

Making a Copy of an Array

Use slice to create a copy of an array. Modifying the copy won’t change the original array.

const array = [3, 4, 5]
const copy = array.slice()
copy.push(6)
console.log(array) // [3, 4, 5]
console.log(copy) // [3, 4, 5, 6]

By the end of this guide, you’ll be well-equipped to handle arrays with confidence. Happy coding!