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([])
Array.from
const fruits = ['🍎', '🍌', '🍐']
const cloned = Array.from(fruits)
Array.slice
const fruits = ['🍎', '🍌', '🍐']
const cloned = fruits.slice()
Spread Operator
const fruits = ['🍎', '🍌', '🍐']
const cloned = [...fruits]
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)
You can also:
Obs.: both are bad practices.
😎
Hahaha, yes. I created this post for LinkedIn. Surprisingly, such posts get a lot more attention than posts that contains valuable information.
Linkedin is just facebook without so much trash today. hahaha
So true! xD
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.
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.