JavaScript (ES6) array methods – Quick Summary

As a person who works with multiple programming languages at a time, I often find it hard to remember the exact methods I need at the moment. JavaScript is one of the main languages for me these days. Here is a list of JavaScript array methods which I tend to use every now and then. Thought putting them in one place may help me from time to time and also other developers.

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

Here is my array for the examples:

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 I am using a very simple callback function which outputs each array element to the console.

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 of an array. If you modify the cloned array, the original array does not get affected and vice versa.

const languages2019 = [...lang];

/* Console Dump from Chrome */
/*
> lang
(3) ["Java", "Python", "JavaScript"]
> const languages2019 = [...lang]
undefined
> languages2019
(3) ["Java", "Python", "JavaScript"]
> languages2019.pop()
"JavaScript"
> lang
(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 … huh, huh?!!

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: My understand was because slice() creates a shallow copy, if I alter the copied array, the original 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 an example:

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

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]

Right … if you’re like me (inquisitive), the first thing that might come to your mind is what is a reducer function? Reducer from a Redux perspective where we are changing the state of each element? Or is it a function which gets passed to every element in the array (kinda like map reduce)? The more I think about it, it is the same thing, unless the function is only reading the value of the elements, in which case the map method is probably more applicable. I suggest you read more this on the MDN page (link above).

Here is the explanation from the text book I use as reference…

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].

For 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.

JavaScript: The Definitive Guide

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 a recruiter wants to find if you know Java

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

Hope this helped you. Keep in mind that there is a lot more to JavaScript arrays than this. Look into forEach, toString and join.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.