Skip to main content

Command Palette

Search for a command to run...

Array Methods You Must Know

Understanding Array Operations with Simple Practical Examples

Published
β€’6 min read
Array Methods You Must Know

If you want to become good at JavaScript especially as a web developer arrays are everywhere.

  • API data comes in arrays

  • Database results come in arrays

  • UI lists are rendered from arrays

If you master array methods, your code becomes:

  • Cleaner

  • Shorter

  • More readable

  • More professional

Let’s understand the most important ones.


push()

This method adds new element(s) to the end of the attached JavaScript array, changing the original array, and returns the new length of the array. This method accepts the elements you wish to add at the end of the array as parameters.

myArray.push(element1, element2, ..., elementX);

Let’s now create a new array then add some more fruits using the push() method:


pop()

This method removes the last element of the attached JavaScript array, altering the original array, and returns the removed element.

myArray.pop();

Note : You don’t pass anything as a parameter to the pop() method.

Here’s an example showing how to use the pop() method:


shift()

The shift() method removes the first element of an array. It works similarly to the pop() method, but instead of removing from the end, it removes from the beginning of the attached array. It returns the removed/shifted element.

myArray.shift();

Let’s now create a new array of animal names and then learn how to use the shift() method to remove the first name from the array:


unshift()

The unshift() method works similarly to the push() method as it is used to add new elements to an array, but to the beginning of an array. This method takes the element(s) you wish to add at the beginning of the array as parameters. It also returns the new length of the array.

myArray.unshift(element1, element2, ..., elementX);

Let’s now create a new array of food names and then add more food names to the array using the unshift() method:


❋ Map, reduce, and filter are all array methods in JavaScript. Each one will iterate over an array and perform a transformation or computation. Each will return a new array based on the result of the function.

Let's Understand these concepts :

✀ Map

map() creates a new array by transforming each element.

‑ It does NOT modify the original array.

Syntax

var new_array = arr.map(function callback(element, index, array) {
    // Return value for new_array
}[, thisArg])

In the callback, only the array element is required. Usually some action is performed on the value and then a new value is returned.

Traditional For Loop vs map()

πŸ”Έ Using For Loop

πŸ”Έ Using map()

So basically the map function maps each every value in the array and transforms it based on a given condition.


✀ Filter()

The filter() method takes each element in an array and it applies a conditional statement against it. If this conditional returns true, the element gets pushed to the output array. If the condition returns false, the element does not get pushed to the output array.

Syntax

var new_array = arr.filter(function callback(element, index, array) {
    // Return true or false
}[, thisArg])

The syntax for filter is similar to map, except the callback function should return true to keep the element, or false otherwise. In the callback, only the element is required.

Examples

In the following example, odd numbers are "filtered" out, leaving only even numbers.

In the next example, filter() is used to get all the students whose grades are greater than or equal to 90.


✀ Reduce()

The reduce() method reduces an array of values down to just one value. To get the output value, it runs a reducer function on each element of the array.

Syntax

arr.reduce(callback[, initialValue])

The callback argument is a function that will be called once for every item in the array. This function takes four arguments, but often only the first two are used.

  • accumulator - the returned value of the previous iteration

  • currentValue - the current item in the array

  • index - the index of the current item

  • array - the original array on which reduce was called

  • The initialValue argument is optional. If provided, it will be used as the initial accumulator value in the first call to the callback function.

Examples

The following example adds every number together in an array of numbers.

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce(function (result, item) {
  return result + item;
}, 0);
console.log(sum); // 10

In the next example, reduce() is used to transform an array of strings into a single object that shows how many times each string appears in the array. Notice this call to reduce passes an empty object {} as the initialValue parameter. This will be used as the initial value of the accumulator (the first argument) passed to the callback function.

var pets = ['dog', 'chicken', 'cat', 'dog', 'chicken', 'chicken', 'rabbit'];

var petCounts = pets.reduce(function(obj, pet){
    if (!obj[pet]) {
        obj[pet] = 1;
    } else {
        obj[pet]++;
    }
    return obj;
}, {});

console.log(petCounts); 

/*
Output:
 { 
    dog: 2, 
    chicken: 3, 
    cat: 1, 
    rabbit: 1 
 }
 */

✀ forEach()

The JavaScript Array forEach() method is a built-in function that executes a provided function once for each array element. It does not return a new array and does not modify the original array. It's commonly used for iteration and performing actions on each array element.

Return value

It does not return a new array. It returns undefined. This method may or may not change the original array provided as it depends upon the functionality of the argument function.


Want More…?

I write articles on blog.prakashtsx.com and also post development-related content on the following platforms:

JavaScript

Part 6 of 6

In this series of blogs I have written some interesting concepts related to JavaScript.

Start from the beginning

Understanding Objects in JavaScript

Understand Objects in JavaScript with very easy way .