ES6 Array Methods - Quick Summary

Love it or hate it, JavaScript is everywhere

As software consultants we work with multiple programming languages at a time. We often find it hard to remember the API details for the language we are working with. JavaScript is one of the main languages for us. Here is a list of JavaScript (ES6) array methods which developers tend to use every now and then. So we thought of putting them in one place for quick reference from time to time.

Of course this isn’t an exhaustive list. Refer to MDN for a complete list.

Sample array

    let lang = ['Java', 'Python', 'JavaScript', 'C#']

push, pop, unshift, shift

push(x): adds element x to the end of the array and returns the length of the array.

lang.push("Go")
// Returns 5 

console.log(lang)
// (5) ["Java", "Python", "JavaScript", "C#", "Go"]

pop(): removes the last element of the array.

let popped = lang.pop(); 
console.log(popped)
// Returns "Go"

unshift(x): adds element x at the beginning of the array and returns the length of the array.

lang.unshift("Go")
console.log(lang)
// (5) ["Go", "Java", "Python", "JavaScript", "C#"]

shift(): removes the first element of the array.

lang.shift()
"Go"

>lang
(5) [""Java", "Python", "JavaScript", "C#"]

map

The map() function takes each element of the array and passes it as an argument to a callback function. Here, we are using a very simple callback function which outputs each array element to the console.

lang.map(l => {console.log("We like programming in " + l)})

// Output
We like programming in Java
We like programming in Python
We like programming in JavaScript
We like programming in C#

filter() + [Digress] Arrow Functions

If the “=>” looks strange, you probably have not come across arrow functions yet. It’s a really concise way of writing functions and enhances code readability. Here is an example:

// Simple ES6 function declaration
const square = function(number) {
  return number * number;
};

// The above can be written as
const squareArrow = number => {
  return number * number;
};

// Real concise way of writing it
const squareArrowConcise = number => number * number;

// Where are arrow functions useful?
const jobs = [
  { id: 1, isActive: true },
  { id: 2, isActive: true },
  { id: 3, isActive: false },
  { id: 4, isActive: true },
  { id: 5, isActive: true },
  { id: 6, isActive: true }
];

// F I L T E R method

// WITHOUT arrow functions
const activeJobs = jobs.filter(function(job) {
  return job.isActive;
});

// WITH arrow functions
const activeJobsArrow = jobs.filter(job => {
  return job.isActive;
});

… (three dots clone operator)

The clone operator allows you to make a deep copy (check out the SO answer) of an array. If you modify the cloned array, the original array does not get affected and vice versa.

const languages2021 = [...lang];

/* Console Dump from Chrome */
/*
> lang
(3) ["Java", "Python", "JavaScript"]
> const languages2021 = [...lang]
undefined
> languages2021
(3) ["Java", "Python", "JavaScript"]
> languages2021.pop()
"JavaScript"
> lang - unchanged
(3) ["Java", "Python", "JavaScript"]
*/

… (three dots spread operator)

Let’s say you have the following two arrays which you want to concatenate.

const firstArray = [1, 2, 3];

const secondArray = [4, 5, 6];

One way (the old way) of doing it would be something like this:

const combined = firstArray.concat(secondArray);

Enter spread operator, the three dots

const combinedUsingSpread = [...firstArray, ...secondArray];

Why bother?!
What if you want to add another element to the combined array …IN THE MIDDLE?

const combinedAndInserted = [...firstArray, -99, ...secondArray];

console.log(combinedAndInserted);
// (7) [1, 2, 3, -99, 4, 5, 6]

splice, slice

From MDN: The slice() method returns a shallow copy of a portion of a typed array into a new typed array object.

slice(start_including, end_excluding)

let lang = ['Java', 'Python', 'JavaScript', 'C#'];

console.log(lang.slice(0, 1));
// "Java"

console.log(lang.slice(0, 2));
// (2) ["Java", "Python"]

console.log(lang.slice(1, 3));
// (2) ["Python", "JavaScript"]

// Original array is unchanged
console.log(lang)
// (4) ["Java", "Python", "JavaScript", "C#"]

IMPORTANT:
A common mistake is to think that since slice() creates a shallow copy, if we alter the copied array, the original array will be altered too. Not the case entirely. For object references, it works that way. But for primitive data types like strings, numbers and booleans, slice() copies the values into the new object (string is not the same and String). So modifying the new array won’t modify the original.

Here is a example:

JavaScript-slice-illustration

slice() – shallow copy works differently for objects and primitive types [check out this SO question]

From MDN: The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements.

splice(start_at_index, number_of_elements_to_remove, elements_to_add)

let lang = ['Java', 'Python', 'JavaScript', 'C#'];

console.log(lang.splice(0, 1));
// "Java"

// Original array has been modified
console.log(lang)
// (3) ["Python", "JavaScript", "C#"]

console.log(lang.splice(0, 2));
// (2) ["Python", "JavaScript"] 

How to add/replace elements to/from an array using splice?

let lang = ["Java", "Python", "JavaScript", "C#"];

// Add PHP into this array of languages right after Java
// Notice second argument is 0, we are not removing anything
lang.splice(0, 0, "PHP"); 

console.log(lang);
// (5) ["Java", "PHP", "Python", "JavaScript", "C#"]

// Replace PHP with C++
// Notice second argument is 1, indicating replacement
lang.splice(1, 1, "C++")

console.log(lang)
// (5) ["Java", "C++", "Python", "JavaScript", "C#"]

How to empty an array using splice?

let lang = ["Java", "Python", "JavaScript", "C#"];

lang.splice(); // removes all elements from the array

reduce

The reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value. [From MDN]

Put is simply, the reduce() method combines the elements of an array using the functions you provide to produce a single value [JavaScript – The Definitive Guide].

Here is an example:

var a = [1,2,3,4,5];

// Sum of values
var sum = a.reduce(function(x,y) { return x+y }, 0);  
console.log(sum);
// 15
// 0 + 1 = 1
// 1 + 2 = 3
// 3 + 3 = 6
// 6 + 4 = 10
// 10 + 5 = 15

// Product of values
var product = a.reduce(function(x,y) { return x*y }, 1); 
console.log(product)
// 120
// 1 * 1 = 1
// 1 * 2 = 2
// 2 * 3 = 6
// 6 * 4 = 24
// 24 * 5 = 120

// Largest value
var max = a.reduce(function(x,y) { return (x>y)?x:y; }); 

reduce() takes two arguments. The first is the function that performs the reduction operation. The task of this reduction function is to somehow combine or reduce two values into a single value, and to return that reduced value. In the examples above, the functions combine two values by adding them, multiplying them, and choosing the largest. The second (optional) argument is an initial value to pass to the function.

reduce() is different from forEach because of the accumulation of the result so far.

includes

Allows you to find if an element is present in a given array. Let’s say someone wants to know if you know Java.

lang.includes("Java")
// will return true

There is much more to JavaScript arrays than these. But if you know how to use the above methods, you definitely know more than an average JavaScript developer. We hope you found this useful.

Thank you for reading!