What's an Array in JavaScript?
In JavaScript, an array is a single variable that is used to store different elements. It is often used when we want to store a list of values and access them by a single variable.
In some cases, you might need to update an array without affecting the original one by making a copy of it.
Cloning an Array in JavaScript
- Using Array.slice() β the fastest way
var arrayToClone = [1, 2, 3]
let clone = arrayToClone.slice(0)
- Using Array.concat()
var arrayToClone = [1, 2, 3]
let clone = [].concat(arrayToClone)
- Using Array.map()
var arrayToClone = [1, 2, 3]
let clone = arrayToClone.map(value => value)
- Spread Operator
var arrayToClone = [1, 2, 3]
let clone = [...arrayToClone]
- Using JSON.stringify() and JSON.parse()
var arrayToClone = [1, 2, 3]
let clone = JSON.parse(JSON.stringify(arrayToClone))
- Defining a custom clone() method
You can create your own clone() method in the prototype of your Array to use it whenever you need it.
var arrayToClone = [1, 2, 3]
Array.prototype.clone = function() {
return this.map(e => Array.isArray(e) ? e.clone() : e);
};
// this is how to use the method
let clone = arrayToClone.clone()
console.log(clone)
If you enjoyed this article, share it with your friends and colleagues!
Keep in touch,
Top comments (0)