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 Learn More

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)

All about JavaScript Arrays Methods

All about JavaScript Arrays Methods

Everything You Need to Know About JavaScript Array Methods

Web development or web programming gave birth to dynamic web applications. With the rise of the web, JavaScript has become one of the most important languages in today’s world. This **JavaScript Array **article will take you to the depths of array methods in JavaScript in the following sequence:

  • Introduction to JavaScript
  • Fundamentals of JavaScript
  • JavaScript Array
  • Difference between Array and Objects
  • JavaScript Array Methods
Introduction to JavaScript

JavaScript is a high level, interpreted, programming language used to make web pages more interactive. It is a very powerful client-side scripting language which makes your webpage more lively and interactive.

It is a programming language that helps you to implement a complex and beautiful design on web pages. If you want your web page to look alive and do a lot more than just gawk at you, JavaScript is a must.

Fundamentals of JavaScript

If you are new to the language, you need to know some of the fundamentals of JavaScript that will help you start writing your code. The basics include:

JavaScript Array

An array is a data structure that contains a list of elements which store multiple values under a single variable.

To declare an array in JavaScript use the ‘let’ keyword with square brackets and enclose all the elements within them. The syntax is as follows:

let ListItems=[];
ListItems=['shoes','watch','bag'];

You can also declare it as:

let ListItems=['shoes','watch','bag'];

Difference between Array and Objects

JavaScript variables can be objects. Arrays are considered to be special kinds of objects. Because of this, you can have variables of different types in the same Array.

myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myItems;

In JavaScript, arrays use numbered indexes. Whereas, objects are used as named indexes.

JavaScript Array Methods

The purpose of using an array is to store** multiple values** in a single entity of a declared variable. Arrays are used when we want to access elements in an orderly fashion using a single variable. One can store strings, boolean and numbers in a single array.

There are different JavaScript array methods in order to perform various tasks such as:
push() – It is easy to remove elements and add new elements while working with arrays. The push() method adds a new element to the end of an array. The return value is the new array length.
Example:

let listItems = ['bag','shoes','dress'];
console.log(listItems.push('watch'));

Output:

4

Push() doest not return the value that has been added to the array. It only returns the new length of the array.
**pop() – **The pop() method is used to remove the last element from an array. It returns the value that has been popped out.
Example:

let listItems = ['bag','shoes','dress'];
console.log(listItems.pop());

Output:

dress

Pop() returns the value that has been removed and not the array length like Push().
shift() – Shifting is similar to popping, working on the first element instead of the last. The shift() method is used to remove the first array element and shifts all other elements to a lower index. It will return you the string that has been shifted out.
Example:

let listItems = ['bag','shoes','dress'];
console.log(listItems.shift());

Output:

bag

Shift() works same as pop() but it returns the first element of the array instead of the last one.
unshift() – The unshift() method adds a new element at the beginning of an array and unshifts older elements. It is similar to Push() and returns the new array length.
**Example: **

let listItems = ['bag','shoes','dress','watch'];
console.log(listItems.unshift('phone'));

Output:

5

Unshift() will add the new element into the array and return the length of the new array.
concat() – The concat() method creates a new array by concatenating or merging existing arrays. It does not modify the existing array and always returns a new array.
Example:

let arr1 = ['red','blue','green'];
let arr2 = ['colors','spraypaint', 'brush'];
let newArr = arr1.concat(arr2);
console.log(newArr);

Output:


toString() – The toString() method is used to convert an array to a string of array values, separated by commas.
Example:

let colors = ['red','blue','green'];
console.log(colors.toString());

Output:

red,blue,green

join() – The join() method works same as toString(). It is used to join all array elements into a string, but in addition, you can specify the separator.
Example:

let colors = ['red','blue','green'];
console.log(colors.join("+"));

Output:

red+blue+green

reverse() – The reverse() method is used to reverse the order of the elements in an array. It will change the original array and swap the order of the elements.
Example:

let fruits = ['mango','apple','grapes'];
console.log(fruits.reverse());

Output:


sort() – The sort() method is used to sort an array alphabetically. This function sorts the values as string by default.
Example:

let fruits = ['mango','apple','grapes'];
console.log(fruits.sort());

Output:


slice() – The slice() method is used to slice out a piece of an array into a new array. It creates a new array without removing any elements from the source array. It will return the value that has been sliced out from the array.
Example:

let colors = ['red','blue','green','yellow','orange'];
console.log(colors.slice(1,3));

Output:

These were some of the most commonly used JavaScript array methods. With this, we have come to the end of our article. I hope you understood how array methods are used in JavaScript.

How to reverse an array in JavaScript?

How to reverse an array in JavaScript?

Here's a Code Recipe to keep around if you need to reverse the order of the elements of an array. You can use the array method, "reverse()" ⏪

Trying a new segment called #CodeRecipes. I want to cover questions that I often google. These are recipes that you should definitely keep handy because it's not a matter "if" you use it, but "when" 😉

const benjamin = ['👶','👦', '👨', '👴'];

const benjaminButton = benjamin.reverse();

console.log(benjaminButton);
// ['👴', '👨', '👦', '👶']

Modifies Original Array

One thing to note is that it mutates the original array.

const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reverse();

console.log(originalArray); // [ 'c', 'b', 'a' ]
console.log(newArray); // [ 'c', 'b', 'a' ]

How to Reverse Array Without Mutating Original Array

Here are some recipes that won't mutate the original array. Let's take a look 👀

Using slice and reverse

const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.slice().reverse();

console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]

Using spread and reverse

const originalArray = ['a', 'b', 'c'];
const newArray = [...originalArray].reverse();

console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]

Using reduce and spread

const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reduce((accumulator, value) => {
  return [value, ...accumulator]
}, []);

console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]

Using reduceRight and spread

const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reduceRight((accumulator, value) => {
  console.log(value);
  return [...accumulator, value]
}, []);

console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]

Or using push

const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reduceRight((accumulator, value) => {
  accumulator.push(value);
  return accumulator;
}, []);

console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]

Source code and tests are available here

Resources

Most Common Array Operations That You Should Learn In JavaScript

Most Common Array Operations That You Should Learn In JavaScript

In this article, we are going to take a detailed look at the most common Array operations that you should learn in JavaScript. These operations are very important in JavaScript programming, especially if you are just starting to learn JavaScript.

Adding Elements

We have 3 methods to add elements to an array, depending on where we want these elements to be inserted.

Array.prototype.push

We can use the push method to add one or more elements to the end of an array.

const numbers = [3, 4];
numbers.push(5, 6); 
// numbers: [3, 4, 5, 6]

Array.prototype.unshift

We can use the unshift method to add one or more elements to the beginning of an array.

const numbers = [3, 4];
numbers.unshift(1, 2);  
// numbers: [1, 2, 3, 4]

Array.prototype.splice

We can use the splice method to add one or more elements somewhere in the middle of an array.

const numbers = [1, 2, 3, 4, 5, 6];
numbers.splice(2, 0, 'a', 'b'); 
// numbers: [1, 2, "a", "b", 3, 4, 5, 6]

The splice method accepts three parameters as shown below.

  • The index where you want to start inserting one or more new elements.
  • The number of elements to remove from the array starting at the index specified in the first parameter.
  • One or more elements to insert into the array at the index specified in the first parameter.
Removing Elements

We have 3 methods to remove elements from an array, depending on where we want these elements to be removed from.

Array.prototype.pop

We can use the pop method to remove the last element of the array and return the value of this element.

const numbers = [1, 2, 3, 4];
var last = numbers.pop();
// last: 4
// numbers: [1, 2, 3]

Array.prototype.shift

We can use the shift method to remove the first element of the array and return the value of this element.

const numbers = [1, 2, 3, 4];
var first = numbers.shift();
// first: 1
// numbers: [2, 3, 4]

Array.prototype.splice

We can use the splice method to remove one or more elements from somewhere in the middle of an array.

const numbers = [1, 2, 3, 4];
var splice = numbers.splice(1, 2);
// splice: [1, 4]

Below are the parameters related to this method for removing one or more elements.

  • The index where you want to start removing one or more elements from the array.
  • The number of elements to remove from the array starting at the index specified in the first parameter.
Complex Array Operations (Higher Order Functions)

We saw the basic adding, and removing items from an array. Now let’s dive into some complex Array operations that come handy when you are coding.

JavaScript comes with some built-in higher-order functions that operate on arrays. You may already be using them, without realising that they are higher-order functions. Let’s take a look at some of them, to understand how they work.

A function that accepts and/or returns another function is called a higher-order function.

Array.prototype.sort

Sorting an array is one of the most common tasks that you will perform during your programming career. The sort() method sorts the elements of an array in place and returns the sorted array. The syntax of the sort() method is below.

arr.sort([compareFunction])

Here the compareFunction refers to the sorting order. This is an optional parameter. If the sort order is not provided, the array elements are converted to strings, then sorted according to each character’s Unicode code point value.

A compare function can take the following form.

function compare(a, b) {
 if (a is less than b by some ordering criterion) {
   return -1;
 }
 if (a is greater than b by the ordering criterion) {
   return 1;
 }
  // a must be equal to b
 return 0;
}

In case you are sorting an array of numbers, then the compare() function is even simpler.

function compareNumbers(a, b) {
 return a - b;
}

The example will sort the array of numbers in ascending order. With the use of the arrow function, the code is simplified further.

let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers);

// [1, 2, 3, 4, 5]

Array.prototype.map

The map() method creates a new array with the results of calling a provided function on every element in the calling array. map() calls a provided callback function once for each element in an array, in order, and constructs a new array from the results.

The callback accepts three arguments:

  • value of the element
  • index of the element
  • array object

You may have used the map() function before. It qualifies as a higher-order function, because it takes in a callback function as an input argument.

var numbers = [1, 4, 9];
var doubles = numbers.map(function(num) {
 return num * 2;
});

// doubles is now [2, 8, 18]
// numbers is still [1, 4, 9]

In the example above, we have an array of numbers and creating a new array using the map(). The map() takes a function as an argument. The argument num within the function will automatically be assigned from each element of the array as map() loops through the original array.

Array.prototype.filter

The filter() method is another example of an in-built higher-order function. It creates a new array with all the elements that pass the test provided by a callback function. The callback function passed to the filter() method accepts three arguments:

  • value of the element
  • index of the element
  • array object

Array elements which do not pass the callback test are simply skipped, and are not included in the new array.

Let’s take a look at an example that shows filter() in action.

function isAboveMyRange(value) {
 return value >= 25;
}
var filtered = [12, 5, 8, 130, 44].filter(isAboveMyRange);
// filtered is [130, 44]

The values that don’t pass this test, will not be a part of the filtered array. The filter() function takes the isAboveMyRange function as an input parameter.

Array.prototype.reduce

Another built-in higher-order function in JavaScript is the reduce() method. It executes the callback function on each member of the calling array, and results in a single output value. The reduce() method takes in two input parameters:

  • The reducer callback function (making this method a higher-order function)
  • Optional initial value
arr.reduce(callback[, initialValue])

The reducer function (callback) accepts four parameters:

  • accumulator
  • currentValue
  • currentIndex
  • sourceArray

If an initialValue is provided, then the accumulator will be equal to the initialValue, and the currentValue will be equal to the first element in the array. Suppose no initialValue is provided, then the accumulator will be equal to the first element in the array and the currentValue will be equal to the second element in the array. Let’s try to understand this better with a simple example.

var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
 return accumulator + currentValue;
}, 0);
// sum is 6

In this example, we have passed an initialValue of zero, this is assigned to the accumulator in the beginning. Every time the reduce() function is called on each value in the array, the accumulator keeps the result of previous operation returned from the function, and the currentValue is set to the current value of the array. In the end the result is stored in the sum variable.

Conclusion

In this article, we learned some common Array Operations in JavaScript.

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about JavaScript

The Complete JavaScript Course 2019: Build Real Projects!

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

JavaScript Bootcamp - Build Real World Applications

The Web Developer Bootcamp

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

New ES2019 Features Every JavaScript Developer Should Know

Best JavaScript Frameworks, Libraries and Tools to Use in 2019

What JavaScript Framework You Should Learn to Get a Job in 2019?

Best JavaScript Frameworks, Libraries and Tools to Use in 2019

Microfrontends — Connecting JavaScript frameworks together (React, Angular, Vue etc)

Ember.js vs Vue.js - Which is JavaScript Framework Works Better for You

Do we still need JavaScript frameworks?