How to Deep Clone an Array in JavaScript

How to Deep Clone an Array in JavaScript

JavaScript offers many ways to copy an object, but not all provide deep copy. Learn the most efficient way, and also find out all the options you have

JavaScript offers many ways to copy an object, but not all provide deep copy. Learn the most efficient way, and also find out all the options you have

Here are 2 ways to deep clone an array. For a quick & dirty way use the JSON methods.

How to Deep Clone an Array

There are 2 types of array cloning: shallow & deep. Shallow copies only cover the 1st level of the array and the rest are referenced. If you want a true copy of nested arrays, you’ll need a deep clone. For deep clones, go with the JSON way OR better yet use Lodash 👍

const numbers = [1, [2], [3, [4]], 5];

// Using JavaScript
JSON.parse(JSON.stringify(numbers));

// Using Lodash
_.cloneDeep(objects);

Arrays are Reference Types

In order to understand why there are two types of cloning. Let’s dig into the fundamentals and explains what are reference types.

Unlike your primitive types (ie. number or string), arrays are reference types. Which means when you assign an array to a variable, you’re assigning a memory address and not the actual array itself. WTH 😱. I know this is a bit confusing. So let’s explain with an example.

Copying a Value type

So no biggie here. We’re creating a copy of value. And if we change the valueCopy, it doesn’t affect the original value. Makes sense - when we change the copy it shouldn’t affect the original at all. All good here 👍

let value = 3;
let valueCopy = value; // create copy

console.log(valueCopy); // 3

// Change valueCopy
valueCopy = 100
console.log(valueCopy); // 100

// ✅ Original NOT affected 
console.log(value); // 3

Copying a Reference type

Okay, things are about to get weird now. Let’s copy our array using the same method as we did to copy a value type.

let array = [1,2,3];
let arrayCopy = array; // create copy

console.log(arrayCopy); // [1,2,3];

// Change 1st element of the array
arrayCopy[0] = '👻';
console.log(arrayCopy); // [ '👻', 2, 3 ]

// ❌Original got affected
console.log(array); // [ '👻', 2, 3 ]

Why did the original array also got affected? That’s because what you copied over is not the array itself but the pointer to the memory space the array occupies. Reference types don’t hold values, they are a pointer to the value in memory.

Solution to Copying Reference Types

So the solution, is to copy over the value NOT the pointer. Like this:

let array = [1,2,3];
let arrayCopy = [...array]; // create TRUE copy

console.log(arrayCopy); // [1,2,3];

// Change 1st element of the array
arrayCopy[0] = '👻';
console.log(arrayCopy); // [ '👻', 2, 3 ]

// ✅ Original NOT affected 
console.log(array); // [ 1, 2, 3 ]

Shallow vs Deep Clone

When I used spread ... to copy an array, I’m only creating a shallow copy. If the array is nested or multi-dimensional, it won’t work. Let’s take a look:

let nestedArray = [1, [2], 3];
let arrayCopy = [...nestedArray]; 

// Make some changes
arrayCopy[0] = '👻'; // change shallow element
arrayCopy[1][0] = '💩'; // change nested element
console.log(arrayCopy); // [ '👻', [ '💩' ], 3 ]

// ❌ Nested array got affected
console.log(nestedArray); // [ 1, [ '💩' ], 3 ]

As you can see, the shallow or first layer is fine. However, once we change the nested element, the original array also got affected. So the solution is to do a deep clone:

let nestedArray = [1, [2], 3];
let arrayCopy = JSON.parse(JSON.stringify(nestedArray)); 

// Make some changes
arrayCopy[0] = '👻'; // change shallow element
arrayCopy[1][0] = '💩'; // change nested element
console.log(arrayCopy); // [ '👻', [ '💩' ], 3 ]

// ✅ Nested array NOT affected
console.log(nestedArray); //  1, [ 2 ], 3 ]

Resources

The JavaScript Developer’s Guide To Node.JS

Introducing TensorFlow.js: Machine Learning in Javascript

Full Stack Developers: Everything You Need to Know

ES5 to ESNext — here’s every feature added to JavaScript since 2015

5 Javascript (ES6+) features that you should be using in 2019

12 Concepts That Will Level Up Your JavaScript Skills

Vuejs 2 Authentication Tutorial

The Complete JavaScript Course 2019: Build Real Projects!

JavaScript: Understanding the Weird Parts

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

The Full JavaScript & ES6 Tutorial - (including ES7 & React)

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

How to Clone an Array in JavaScript?

In this JavaScript tutorial, you'll learn how to clone an array in JavaScript. Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array.

JavaScript Array.flatMap()

JavaScript Array.flatMap(): Use flatMap to map over an array and flatten the result array in one go! Now lets up the game and introduce "flatMap". It combines the steps of first mapping over the array with `map()` & then calling `flat()`. Instead of calling 2 methods, just use `flatMap()` 👍