Copying JavaScript arrays is something that we’ve to do often in our apps.
In this article, we’ll look at how to copy a JavaScript array by its values.
Array.prototype.slice
We can use the slice
method available in a JavaScript array instance.
For instance, we can write:
const oldArray = [1, 2, 3, 4, 5];
const newArray = oldArray.slice();
console.log(newArray);
The slice
method returns a copy of the array it’s called on if no arguments are passed into it.
Spread Operator
Another way to copy an array’s entries into another array is to use the spread operator.
This is available since ES6.
For instance, we can write:
const oldArray = [1, 2, 3, 4, 5];
const newArray = [...oldArray];
console.log(newArray);
We copy all the items from the oldArray
into the newArray
with the spread operator.
So newArray
is the exact copy of oldArray
.
Array.prototype.concat
We can also use the concat
method to copy an array to a new array.
To use it, we can write:
const oldArray = [1, 2, 3, 4, 5];
const newArray = [].concat(oldArray);
console.log(newArray);
concat
returns the array it’s called on with the array that’s passed into it as the argument.
Also, we can write:
const oldArray = [1, 2, 3, 4, 5];
const newArray = oldArray.concat();
console.log(newArray);
which also returns a copy of oldArray
.
JSON.stringify and JSON.parse
We can use JSON.stringify
and JSON.parse
to make a copy of an array.
For instance, we can write:
const oldArray = [1, 2, 3, 4, 5];
const newArray = JSON.parse(JSON.stringify(oldArray));
console.log(newArray);
JSON.stringify
converts oldArray
to a JSON string.
Then we use JSON.parse
to convert the JSON string back to an array.
And then we assigned the returned value to newArray
.
Array.from
Another way to copy an array is to use the Array.from
method.
The method lets us create an array from other arrays or an array-like object.
To use it to copy an array we can write:
const oldArray = [1, 2, 3, 4, 5];
const newArray = Array.from(oldArray);
console.log(newArray);
We just pass in the array we want to copy into the method and it’ll be copied.
Lodash
Lodash has the clone
method to do a shallow clone of an object.
It also has the cloneDeep
method to do a deep clone of an object.
We can use either one to copy an array.
For instance, we can write:
const oldArray = [1, 2, 3, 4, 5];
const newArray = _.clone(oldArray)
console.log(newArray);
or:
const oldArray = [1, 2, 3, 4, 5];
const newArray = _.cloneDeep(oldArray)
console.log(newArray);
to make a copy of oldArray
and assign it to newArray
.
Conclusion
There are many ways to copy an array into another one with JavaScript’s standard libraries.
We can also do the same thing with Lodash.