Skip to content

Different ways of copying an array in JavaScript

This time, I thought of sharing the different ways of copying an array in JavaScript and intended to keep this post as much as short.

Introduction

We should always in need of this, taking a copy of an array in order to manipulate the values. Some of us have done the mutation on the original array rather than taking a copy of it.

To the upfront, we should always avoid mutating the original object. This is the thing every other JavaScript framework/library suggesting to follow in their codebase.

Why because everyone suggests this way here is that, to trace the object value change. The most popular front-end UI library React done this part well enough.

Quick Tip:

Based on this principle, we have one JavaScript library Immutable.js that got huge developer’s attention.

Different ways of copying an array

let’s consider we have the valuesarray.

const values = [{name: 'Jack'}, {name: 'Varshan'}, {name: 'Jordhan'}];

One,

const values_copy = values.slice(0);

The above way will help us to take shallow copy of an array which is taking only the structure not its internals.

Two,

const values_copy = [...values];

This pattern we got introduced from ES6seems easy to memorize and does the same job as the previous way.

That’s it. If you people have some more ways to copy an array please post it in the comments section.

Published inAngularFrameworksJavaScriptReact