Learning about the JavaScript array methods to manipulate data is crucial to producing clean, readable, and concise code when working with lists. Manual loops and conditions can be used to accomplish data manipulation, however many developers would rather rely on pre-built JavaScript array methods to make the process of manipulating the data much easier.
In essence, JavaScript array methods are very similar to using specialized tools in a box full of tools. Each tool provides a unique service. Many of the methods allow you to add or delete elements from an array. Most of the remaining methods provide various ways to perform some type of operation with the elements of an array. Some of the methods create a new array of the results of that operation. Other methods produce a single result, such as a total of the elements.
As a beginner learning about arrays, begin with basic concepts related to arrays, including creating an array, accessing individual elements within the array, and basic loops. However, to utilize arrays effectively, you should learn about the methods that can be used with arrays. Below are 5 primary categories of JavaScript array methods:
1. Adding/Removing Elements from Arrays
These methods modify the original array by either adding or removing individual elements. The best ways to accomplish this include:
- push() adds one or multiple elements to the end of an array. It also returns the new size of the array. Using this method allows you to easily add elements to the end of an array, such as adding a new task to a list of to-do items.
- pop() removes an element from the end of an array and returns it. If you wish to reverse the last action that was taken or if you need to implement a stack, then this method is ideal for those needs.
- unshift() adds one or more elements to the beginning of an array. Since all of the previously added elements will now have a new index that is larger, this method will increase the size of the array. This method will typically be slower than using push(), since pushing onto the end of an array is faster than inserting at the beginning. However, this method may be needed depending on how your application requires ordering items, such as placing a priority item in front of a non-priority item in a queue.
- shift() removes an element from the beginning of an array and returns it. As stated above with unshift(), because all other elements will now have a new index that is smaller due to the removal of an element at the beginning of the array, this method will decrease the size of the array. Similar to unshift(), this method will typically be slower than using pop(), since removing an element from the end of an array is faster than removing from the beginning. However, this method may be necessary if you wish to process items in order, such as displaying each product in a shopping cart in sequence.
- splice() is the most robust mutator method available for arrays. This method can remove elements from anywhere in the array, replace elements, or insert elements into the array at any point. The first argument to this method is where you wish to begin splicing (i.e., removing) elements. The second argument indicates how many items you wish to remove from the array. Any additional arguments indicate where you wish to place the removed items back into the array. Be careful using this method, since it modifies the original array directly.
2. Iteration Methods: Performing Actions on Every Element
Sometimes there is nothing else to do with every element except perform some kind of action on each element without having to create a new array. In cases such as logging information after processing every item in an array, updating the Document Object Model (DOM), or saving processed information somewhere, these types of methods are usually sufficient.
forEach() calls a provided function once for every element in the array. The function passed into forEach() has access to three parameters: the current value being processed (the element), its index in the array, and the entire array itself. This type of method is generally considered better than traditional for loops when you don’t need to exit early during looping nor when you need to modify the original array while looping over it.
Unlike both map() and filter(), this type of method does not return anything. Its sole purpose is to perform actions. For example, you could use this type of method to display each product in a shopping cart on a web page.
3. Transformations Methods: Creating New Arrays
These types of methods represent the core of functional data processing. They do not alter the original array but instead generate a new array created from transforming each element of the original.
- map() generates a new array generated by calling a function on each element in an original array. The resulting new array will contain all of the same amount of elements as the original but each value will have been altered in some way. Examples of using map() could include changing data formats, pulling out properties, or doing calculations. For example, you could have an array consisting of user objects and map that into an array consisting solely of their names.
- filter() generates a new array containing only elements which meet a test criteria. A function that determines whether an element should be included is called a test function. This function returns true if an element is to be kept in the resultant array and false otherwise. This type of method is how you determine all active users, all even numbers, or all completed tasks.
- slice() generates a shallow copy of an array segment (portion). No changes are made to the original. You simply call slice() and identify which part of the original array you wish to copy by providing two indices: a starting index and an ending index. The returned value will be another new array representing that portion of the original. This is commonly utilized for pagination purposes or obtaining first ‘n’ number of items.
- concat() combines two or more arrays into a new array. While the spread operator (…) has proven to be more convenient than utilizing concat(), there are still valid reasons why you may choose to use it.
4. Search and Test Methods
There are times when you simply need to locate something specific or examine some condition against each item in an array. In cases like these, these types of methods help you avoid manually implementing a loop yourself.
- find() returns the first element that satisfies a testing function. If no such element exists within the array, then it returns undefined. If you need to obtain the actual object itself based upon identifying a particular item by means of ID within an array, then find() is your choice.
- findIndex() works similarly to find() but instead finds the index where the first matching element resides, returning -1 if no such element exists. You would likely utilize this when you need to eventually update items within your data structure.
- includes() determines whether a particular value exists within an array. It returns Boolean. This is likely going to be your fastest route to determining if a primitive value (number or string) exists within an array.
- indexOf() and lastIndexOf() return the first or last index where a particular value is located (or -1 if it cannot be found). Depending on your needs and requirements for your project (such as needing positional references as opposed to simply knowing if something exists), these functions can be helpful.
- some() returns true if at least one element meets test criteria. Utilize some() when checking if any item(s) satisfy a certain condition (for example, whether a shopping cart includes products that are currently out of stock).
- every() returns true only if all elements meet test criteria. Consider using every() when validating input fields exist for forms or when verifying all items exist for inventory.
5. Reduction & Aggregation Methods
These types of methods take an array and combine its elements together into one overall element (value). After mastering these types of methods and understanding how they work, you’ll be able to perform complex manipulations on your data.
- reduce() is probably one of the most flexible methods available for reducing arrays. With reduce(), you can iterate through an array and accumulate (add up) values as you go along. You can sum numbers, flatten nested arrays (arrays inside arrays), count occurrences (how many times a certain value occurs), and/or create entirely new data structures. The callback function for reduce() accepts three parameters: accumulator (previous accumulated value), current value (current element being processed), and optionally, an initial value for accumulation.
- reduceRight() operates exactly like reduce() but traverses through arrays from right-to-left instead of left-to-right. Although reduceRight() is less frequently used than reduce(), it still has utility in certain operations (for example, reversing strings).
- join() concatenates all elements within an array into one string (a single line of text). An optional parameter can be passed indicating a delimiter (character or characters separating individual elements). By default, join() will concatenate elements with commas as delimiters. Join() is ideal for generating display strings from lists (e.g., taking an array of tag names and joining them into a comma-separated string).
Conclusion
These five primary categories – adding/removing, iteration, transformation, search/test, and aggregation/reduction will cover nearly all your needs regarding how to utilize JavaScript array methods.
Begin with basic concepts such as creating arrays, accessing individual elements within an array, and basic loops before moving on to learning about the methods associated with arrays. Once familiar with these methods, try experimenting with some of them together (for example filter and find).
Once you’re proficient with all of them individually, focus on mastering reduce(). Understand that it takes time for reduce() to click; however, when it does click for you, you’ll see that it’s well worth investing your time.
Once you’ve mastered JavaScript array methods, your development workflow will improve significantly. Your code will be simpler, cleaner, and easier to manage.
Quick Reference List
Below is a list you can refer to as you continue learning about JavaScript array methods:
- Use push and pop when dealing with stacks (last in / first out).
- Use unshift and shift when dealing with queues (first in / first out); however remember they are slower.
- Use forEach when you need side effects (logging, DOM updates etc…).
- Use map when transforming every element; create new array same size as original.
- Use filter when selecting subset; keep only items meeting test criteria.
- Use find when looking for specific item; stops at first match.
- Use some when testing for existence; some tests for “at least one” whereas every tests for “all”.
- Use reduce when doing complex accumulation; summing numbers, flattening nested arrays etc…
- Keep in mind that most methods do not affect original arrays; splice & mutators are exceptions.
MDN Array Method Guide
A good source for further reading on these subjects is Mozilla Developer Network’s Array Methods Guide which includes several detailed examples.
Another good resource is JavaScript.info’s article on Array Methods which focuses on explaining each subject clearly and concisely for beginners.
By becoming familiar with these tools, you will dramatically enhance how you interact with data and ultimately develop more readable and efficient code.
New to HTML? Start Here: HTML Tutorial for Beginners: Your Complete Introduction to HTML Basics
New to CSS? Start Here: CSS Introduction: Master 5 Core Concepts Easily
New to JavaScript? JavaScript Introduction: 5 Proven Steps to Learn JS
[INSERT_ELEMENTOR id=”122″]

