Explain Codes LogoExplain Codes Logo

Copy array by value

javascript
array-cloning
shallow-copy
deep-copy
Alex KataevbyAlex Kataev·Aug 3, 2024
TLDR

Duplicate an array without maintaining references to original items using the spread operator:

const oldArray = [1, 2, 3]; const newArray = [...oldArray]; // Meet the new array, not same as the old array!

For copying all dimensions including nested objects (deep cloning), apply JSON.parse and JSON.stringify:

const deepCopiedArray = JSON.parse(JSON.stringify(oldArray));

Warning: JSON technique eliminates functions and struggles with unique objects (like Dates). Utilize library functions for more complex requirements.

Shallow vs. deep cloning: The basics

When cloning arrays in JavaScript, you'll encounter two fundamental methodologies: shallow copy and deep copy. In simple terms:

  • Shallow copy: Crafts a new array with the same elements up to the first level. Good for barbeques!
  • Deep copy: Reproduces all levels, essential when the party moves indoors.

Remember, shallow copy methods clone successfully with primitive values (number, string, boolean). However, objects (arrays, functions, dates, custom objects) keep their references in a shallow copy. They can't let go!

Handy methods for cloning arrays

There's more than one way to clone an array, just like there's more than one way to peel a banana.

  • slice() method: Copies items, perfect for primitive types.
    const slicedArray = oldArray.slice(); // Same slice, different pie!
  • Spread syntax or [...]: Does the same job as slice(), just a younger, sprightlier model.
    const spreadArray = [...oldArray]; // Spread the love... or the array!
  • concat() function: Appends to an empty array, another weapon in your shallow cloning arsenal.
    const concatenatedArray = oldArray.concat(); // Concat’ed a new one!

Advanced cloning: Deep thoughts

Sometimes, a shallow copy isn't enough. You need to dig deeper (get it?). There are tools to handle that.

  • Lodash: Gives you _.cloneDeep(), takes care of deep copying, and even makes your morning coffee.
  • jQuery: Offers $.extend(), ideal for cloning arrays inside and out.

Even more advanced cloning: The edge cases

Circles within circles

If your array references itself (we call them 'circular references'), be careful! Shallow copy methods can lead you into an infinite loop.

Transpilation for compatibility

TypeScript and Babel can compile spread syntax and other fancy ES6+ features, to play nicely with legacy browsers.

Speed is key

Deep copies can be slow on older JavaScript engines and browsers. Don’t forget to benchmark any method used in production.

Know the objects inside out

If your array contains literals, structures, or prototype-based beings, pick your cloning method accordingly.

Array cloning: Best practices

When cloning arrays, following several simple rules will save you hours of debugging:

  1. Don't use new Number(), new String(), new Boolean() constructs for cloning.
  2. Confirm compatibility with your target browsers before using ES6 features.
  3. JSON.parse(JSON.stringify()) isn't always a straight answer. It omits functions, undefined, and any other non-serializable entities.
  4. When cloning complex objects, library functions from reliable sources like Lodash or jQuery are your best friends.