loading...
Cover image for Useful JavaScript array methods

Useful JavaScript array methods

phyllis_yym profile image Phyllis Yu Yu💫 Updated on ・5 min read

Array is one of the most frequently used data structure in JavaScript. It is an object that can store a collection of values of the same type. For example, comments of a blog post or images in a carousel can be stored in an array.

There are a lot of built-in array methods which can help us add, remove or manipulate data. This article will cover a number of common array methods, which are grouped by the purpose of data transformation.

Table of content

  1. Insert - push, unshift
  2. Remove - pop, shift
  3. Remove/ replace / insert - splice
  4. Slice - slice
  5. Merge - concat
  6. Search - includes, find, findIndex, indexOf
  7. Reverse - reverse

Insert - push, unshift

Add it to the list

  • push: This method can be used when you want to add one or more items to the end of an array. The original array will be transformed with the addition of the new item. The method itself will return the new length of the array.
let tea = ['breakfast','lemon','green'];
let count = tea.push('peach');
console.log(tea);
//['breakfast','lemon','green','peach']
console.log(count);
// 4

tea.push('black','strawberry','cranberry');
console.log(tea);
//['breakfast','lemon','green','peach','black','strawberry','cranberry']
  • unshift: This method adds one or more items to the beginning of an array. Same as 'push', the array in place will be modified and the function itself returns the new length of the array.
let letters = ['a', 'b', 'c', 'd', 'e'];
let count = letters.unshift('x', 'y', 'z');
console.log(letters);
//['x', 'y', 'z', 'a', 'b', 'c', 'd', 'e'];
console.log(count);
// 8

Remove - pop, shift

Cross out

  • pop: It removes the last item from an array. The original array will be transformed with the removal of the last item. The function itself returns the deleted item.
let letters = ['a', 'b', 'c', 'd', 'e'];
let poppedItem = letters.pop();
console.log(letters);
//['a', 'b', 'c', 'd']
console.log(poppedItem);
//'e'
  • shift: This removes the first element from an array. Again, the array in place will be changed and the function returns the deleted element.
let letters = ['a', 'b', 'c', 'd', 'e'];
let shiftedItem = letters.shift();
console.log(letters);
//['b','c', 'd', 'e']
console.log(shiftedItem);
//'a'

Remove/ replace / insert - splice

  • splice: This method modifies the content of an array by removing or replacing existing elements and/or adding new elements. The original array will be changed.

The syntax would be

let modifiedArray = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

Example 1: at index 0, delete two items "salad" & "steak"

let food = ['salad', 'steak', 'pudding', 'carrot cake'];
food.splice(0,2);
console.log(food); 
//["pudding", "carrot cake"]

Example 2: at index 1, delete zero items and insert "snake" and "rabbit"

let animals = ["koala", "fish", "tortoise", "whale"]
animals.splice(1,0,"snake","rabbit");
console.log(animals); 
//["koala", "snake", "rabbit", "fish", "tortoise", "whale"]

Example 3: at index 0, delete two items "earl grey" & "lemon" and replace them with "breakfast" & "peach"

let tea = ["earl grey", "lemon", "green"];
tea.splice(0, 2, "breakfast", "peach");
console.log(tea); 
//["breakfast", "peach", "green"]

Slice - slice

slice

  • slice: This method returns a desired portion of an array from your specified start point and before your specified end point. Negative index can be passed in and it will count backwards from the end of an array. If the end point is not specified, the rest of the array will be returned. If the start point and end point are not specified, it returns a copy of the whole array. One thing to note - it does not modify the original array but returns the desired portion.
let food = ['steak', 'pasta', 'cake', 'pudding', 'salad', 'soup'];
let copy = food.slice();
console.log(copy);
//['steak', 'pasta', 'cake', 'pudding', 'salad', 'soup']
let dessert = food.slice(2, 4);
console.log(dessert);
//['cake', 'pudding']
let starter = food.slice(-2); 
console.log(starter);
//['salad', 'soup']
let sweets = food.slice(-4, -2);
console.log(sweets);
//['cake', 'pudding']

Merge - concat

  • concat: This method is used to merge two or more arrays. The original arrays will not be changed. The function itself returns a new array.
let tea = ['breakfast','earl grey','green'];
let juice = ['orange', 'pineapple', 'pear'];
let drinks = tea.concat(juice);

console.log(drinks);
//['breakfast','earl grey','green','orange','pineapple', 'pear']

console.log(tea);
//['breakfast','earl grey','green']

console.log(juice);
//['orange', 'pineapple', 'pear']

Search - includes, find, findIndex, indexOf

Search

  • includes: This methods returns a boolean whether an array contains an element we are looking for. The second argument, which indicates the index to start searching at, is optional.
let tea = ['breakfast','earl grey','green'];

console.log(tea.includes('breakfast')); 
// true
console.log(tea.includes('strawberry'));
//false
console.log(tea.includes('earl grey', 1));
//true
console.log(tea.includes('earl grey', 2));
//false
  • find: If you have a search criteria, you may consider using this method. This returns the first item which satisfies the criteria specified by you. If the item cannot be found, undefined is returned.

In the first example below, the criteria states that the number we look for should be bigger than 3. The search function will return 4 because 4 is the first element in the array that meets the criteria.

In the second example below, the criteria states that the number needs to be smaller than 1. The search function will return undefined because none of the elements in the array meets this criteria.

let numbers = [ 1, 2, 3, 4, 5, 6];
let found = numbers.find(num => num > 3);
console.log(found);
// 4
found = numbers.find(num => num < 1);
console.log(found);
// undefined
  • findIndex: This method is almost the same as find. Find returns the first matching item as per the specified criteria, whereas findIndex returns the index of first matching item. It returns -1 if no matching item is found.

In the first example below, the criteria states that the number needs to be bigger than 3. The search function will return 1 because 1 is the index of number 4, which is the first number matches the criteria.

In the second example below, the criteria states that the number needs to be smaller than 2. The search function will return -1 because none of the numbers in the array is smaller than 2.

let numbers = [ 2, 4, 6, 7, 9, 10];
let foundIndex = numbers.findIndex(num => num > 3);
console.log(foundIndex);
// 1
foundIndex = numbers.findIndex(num => num < 2);
console.log(foundIndex);
// -1
  • indexOf: This method is almost the same as findIndex, but instead of taking a function as the search criteria and argument, this takes a value. The second argument, which indicates the index to start searching at , is optional.
let juice = ['orange', 'pineapple', 'pear'];
let index = juice.indexOf('orange');
console.log(index);
// 0
index = juice.indexOf('orange', 1);
console.log(index);
// -1

Reverse - reverse

reverse

  • reverse: This method reverses an array by modifying the original array.
let array = ["Y", "P", "P", "A", "H"];
let reversed = array.reverse();
console.log(reversed);
// ["H", "A", "P", "P", "Y"]

Thank you for reading this article! This article is far from comprehensive. There are still many methods which have not been covered. If you want to find out more about JS array methods, you can check out the docs on MDN. It's really good reference for learning and understanding how they work.

Buy Me A Coffee

Posted on Jun 25 by:

phyllis_yym profile

Phyllis Yu Yu💫

@phyllis_yym

// Buyer working my way to transition into Web Development👩🏻‍💻 // Always curious and learning

Discussion

markdown guide
 

Hi Phyllis! This is definitely a nice cheat sheet! Thank you and keep it up!💪

 

Hi Jason! Thanks for your support, much appreciated !

P.S. I’m from Hong Kong too👋🏻

 

我知呀! I am happy I found another Hong Kong web developer here! 🤩

我都好開心!You are the first Hong Kong web developer I met here and on Twitter 🤩

Feel free to drop me a DM anytime you need help. Not an expert, but happy to share what I know. 😉

Thanks for your offer!! I will drop you a message when I get stuck :)

 
 

Incredible information and formatted in an easy to read and understand way!

Thank you for sharing, bookmarking this one for future reference!!

 

Thanks Devin! Really appreciate your support :)

 

What about all the FP-style HOFs?
map, flatMap, filter, fold, ...

 

Thank you for information. That's awesome. I had freshen old information after the article :)

 
 

Very nice :) thanks for sharing!
But what about sort(callback), filter() and reduce()?
They can come pretty handy ;)

 

Thanks for your suggestion! I may add these methods in this article later.

 

Awesome guide for these practical methods! Thanks

 

Thanks! Glad you found it helpful :)