DEV Community

Rebecca Womack
Rebecca Womack

Posted on • Edited on

10 Array Methods You Should Know 👀

The Basics 🕺

So what are arrays? 🤔

ar·ray /əˈrā/ noun 1. an ordered series or arrangement.
In computer science, an array data structure, or simply an array, is a data structure consisting of a collection of elements, each identified by at least one array index or key. An array is stored such that the position of each element can be computed from its index tuple by a mathematical formula.

In JavaScript, arrays are basically a data structure that holds a list of values. These values can be strings, integers, or even objects. Arrays don't have fixed types or restricted lengths.

Arrays are referenced using square brackets: [] The index of an element simply means the "location" of the element in the array. You count the index of an element by starting at 0 rather than 1. For example, newArray = [1, 2, 3, 4];. In this case, 1 is in the 0th place.

You can retrieve an item by using its index with brackets []. For example: newArray[0] That will return 1. newArray[2] will return 3.
Another example would be let cats = ["Sebastian", "Emmy", "Mr.Whiskers"]; cats[1] would return "Emmy"

If you know those basic concepts, you can begin to learn array methods. You'll quickly find that there are a variety of different methods out there can make your logic streamlined and efficient. Here are 10 commonly used methods to master. 🆒

Methods 🥳

1) .push() | adds an element to the end of an array

       let names = ["Nick", "Chris", "Ben"];
       names.push("Rebecca"); 
       console.log(names);
       // names = ["Nick", "Chris", "Ben", "Rebecca]; 
Enter fullscreen mode Exit fullscreen mode

2) .pop | removes the last element in an array

       let cities = ["New York", "Los Angeles", "Atlanta"]; 
       cities.pop(); 
       console.log(cities); 
       // cities = ["New York", "Los Angeles"];
Enter fullscreen mode Exit fullscreen mode

3) .shift | removes the first element an array

       let ages = [30, 26, 24, 20];
       ages.shift(); 
       console.log(ages);
       // ages = [26, 24, 20]
Enter fullscreen mode Exit fullscreen mode

4) .unshift | adds an element to the beginning of an array

       let ages = [30, 26, 24, 20];
       ages.unshift(60); 
       console.log(ages);
       // ages = [60, 30, 26, 24, 20];
Enter fullscreen mode Exit fullscreen mode

5) .splice | adds, removes, or replaces an element at a given index. The first parameter is the index, the second parameter is how many elements you want to remove, and the 3rd parameter is the value you want to replace or add.

       // to remove elements
       let animals = ["cat", "dog", "shark", "horse", "alligator"]; 
       animals.splice(1, 2); 
       // remove 2 elements at index 1, including index 1
       // so what's being "spliced" is "dog" and "shark"
       console.log(animals);
       // animals  = ["cat", "horse", "alligator"];
Enter fullscreen mode Exit fullscreen mode
       // to add elements
       let animals = ["cat", "dog", "shark", "horse", "alligator"]; 
       animals.splice(2, 0, "zebra"); 
       // at index 2, splice (or remove) 0 elements, add "zebra" 
       animals  = ["cat", "dog", "zebra", "shark", "horse", "alligator"]; 
Enter fullscreen mode Exit fullscreen mode
       // to replace elements
       let animals = ["cat", "dog", "shark", "horse", "alligator"]; 
       animals.splice(2, 1, "zebra"); 
       // an index 2, replace 1 element ("shark") with "zebra"
       // at index 2, splice (or remove) 0 elements, add "zebra" 
       animals  = ["cat", "dog", "zebra", "horse", "alligator"]; 
Enter fullscreen mode Exit fullscreen mode

6) .slice | returns a shallow copy of an array. It can take one or two parameters that represent the "beginning" and "end" of where you want to slice. Note that the "beginning" parameter is included whereas the "end" parameter should not be included.

       let colors = ["Blue", "Red", "Orange", "Purple", "Pink"];
       let lessColors = colors.slice(1, 3);
       console.log(lessColors); 
       // colors = ["Red", "Orange"];
Enter fullscreen mode Exit fullscreen mode

👉 If you only include one parameter, it'll keep every element after the "beginning" value.

       let colors = ["Blue", "Red", "Orange", "Purple", "Pink"];
       let lessColors = colors.slice(2); 
       // colors[2] = "Orange" which now becomes the 1st element
       console.log(lessColors);
       // lessColors = ["Orange", "Purple", "Pink];
Enter fullscreen mode Exit fullscreen mode

❗️ .splice vs .slice can be hard to remember. Think of splice as a very dynamic method with the ability to remove, replace, or add elements and modifies the existing array... whereas slice mainly removes values and creates a new array.

7) .forEach | performs a function for each element in an array

       let miles = [1, 3, 5, 10];
       let moreMiles = [];
       miles.forEach(element => moreMiles.push(element + 10))
       console.log(moreMiles);
       // [11, 13, 15, 20];
Enter fullscreen mode Exit fullscreen mode

8) .map | creates a new array with the result of executing the provided function to each element in the array

       let population = [200, 600, 170, 100];
       let doublePopulation = population.map(element => element * 2);
       // we are assigning the result of mapping to doublePopulation
       // we would not be able to do this with the .forEach method
       // because it returns undefined
       console.log(doublePopulation);       
       // [400, 1200, 340, 200]
Enter fullscreen mode Exit fullscreen mode

❗️ Note that the difference between .forEach and .map is that when you call the .forEach method, it returns undefined and .map returns a new array!

9) .reduce | combines (or reduces) the array into one single value. A simple way to learn the reduce method is to add together all elements in an array. The method takes two parameters, the accumulator and the current value.

       let ticketPrices = [99.54, 56.43, 122.94];
       let totalCostOfTickets = ticketPrices.reduce((total, amount) => total + amount)
       // the accumulator is total; it's holding the new values as you add
      // the amount is the next ticket price. 
       totalCostOfTickets = 278.91

Enter fullscreen mode Exit fullscreen mode

10) .filter | creates a new array with the elements that pass the provided function.

       let names = ["Rebecca", "Chris", "Ben", "Rachel"];
       names = names.filter(name => name[0] === "R") 
       // this is looping through each name and checking if 
       // the first index of the string (aka first letter) is "R".
       console.log(names):
       // names = ["Rebecca", "Rachel"];
Enter fullscreen mode Exit fullscreen mode
       let ages = [16, 21, 26, 14];
       ages = ages.filter(age => age >= 21) 
       // this is looping through each age and checking if  
       // the value is greater than or equal to 21.
       console.log(ages):
       // ages = [21, 26];
Enter fullscreen mode Exit fullscreen mode

There are many more methods out there, but these are super helpful to keep in your tool belt! 🙌 Thanks for reading, and feel free to reach out if you have any feedback on this article or any questions!

Top comments (13)

Collapse
 
madza profile image
Madza

always have to open docs for slice and splice :)

Collapse
 
karataev profile image
Eugene Karataev

For me slice is nice and handy method to take a part of an array without mutating the original.
splice on the other hand is like a monster, because it mutates the original array.
splice

Collapse
 
nick profile image
Nick

Haha, soo true.

Collapse
 
joshmedeski profile image
Josh Medeski

I'm so thankful for .map now. We used to have to do for loops manually and push to a new array!

Collapse
 
aritdeveloper profile image
Arit Developer

excellent post! thanks for sharing!

Collapse
 
saravanaworkspaces profile image
Saravana kumar Chinnaraj • Edited

Hey Nice article, But can you check shift() and unshift() once again ASAP.

And map example too "numberOfWins".

Collapse
 
rebeccauranga profile image
Rebecca Womack

Thanks so much for pointing those out! I appreciate your feedback.

Collapse
 
michaelwomack profile image
Michael Womack

Great post! I would love to read a part 2.

Collapse
 
tobiasramzy profile image
Tobias

Thank you 🥺

Collapse
 
abdulghani200 profile image
Abdul Ghani

Nice and informative. Thanks for sharing ♥️

Collapse
 
arilength profile image
ari.length

Simple and efficace post thanks !! :)

Collapse
 
abraham profile image
Abraham Williams

A complementary resource is doesitmutate.xyz/. It'll tell you if an array method mutates the value or copies it.

Collapse
 
hadmouse profile image
Fabián Vera

"(Reduce) method takes two parameters, the accumulator and the current value" That's pretty reductive (no pun intended), since it takes four.