DEV Community

Muhammad Hasnain
Muhammad Hasnain

Posted on

Four Ways to Clone Array with Ease! Easiest Method to Clone Array.

Visit my personal blog for more awesome content. hasnain.dev

Unlike primitive types, arrays cannot be cloned by simply assigning them to another variable, doing that only stores reference in another variable. Fear not! There are plenty of ways in which you can make a new copy of an array using four methods!

Array.concat

const fruits = ['🍎', '🍌', '🍐']

const cloned = fruits.concat([])
Enter fullscreen mode Exit fullscreen mode

Array.from

const fruits = ['🍎', '🍌', '🍐']

const cloned = Array.from(fruits)
Enter fullscreen mode Exit fullscreen mode

Array.slice

const fruits = ['🍎', '🍌', '🍐']

const cloned = fruits.slice()
Enter fullscreen mode Exit fullscreen mode

Spread Operator

const fruits = ['🍎', '🍌', '🍐']

const cloned = [...fruits]
Enter fullscreen mode Exit fullscreen mode

Best Practice

Some of these aren't best practice. It really depends on what you're trying to achieve. For instance, Array.from converts iterables into an array. Array.concat concatenate two arrays. Array.slice gives you a part of an array and the spread operator simply spreads an array into argument list.

Best practice depends on what purpose you are using these methods for.

Top comments (6)

Collapse
 
davispindola profile image
Spindola • Edited

You can also:

const arr = [1, 2, 3]

// with map
const cloned_with_map = arr.map(i => i)

// with reduce + flat
const cloned_with_reduce = 
  arr.reduce((a, b) => [a, b])
  .flat()

Array.of(arr).flat()
Enter fullscreen mode Exit fullscreen mode

Obs.: both are bad practices.

😎

Collapse
 
hasnaindev profile image
Muhammad Hasnain • Edited

Hahaha, yes. I created this post for LinkedIn. Surprisingly, such posts get a lot more attention than posts that contains valuable information.

Collapse
 
davispindola profile image
Spindola • Edited

Linkedin is just facebook without so much trash today. hahaha

Thread Thread
 
hasnaindev profile image
Muhammad Hasnain

So true! xD

Collapse
 
amt8u profile image
amt8u

Just remember that all these methods just get you a new array with copied values for single level only. For any nested objects or multi dimensional arrays you need to access each and every value and copy it by yourself.

Collapse
 
hasnaindev profile image
Muhammad Hasnain

Thanks for pointing that out. The idea is to know how to clone a single array. When it comes to nesting, same rules or methods apply. However, it is much better to use an npm package to clone deep and nested objects recursively. Thank you.