Cloning an array might seem like a daunting task at first, but with JavaScript ES6, it has never been easier. This post will show you an easy and declarative way to copy or clone the value of an array with Javascript. But also to clone in a more simple way using a Spread Operator!
Cloning with Array.from
To copy an array, we cannot just use =
because it will copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array into a new variable.
By doing so, the new array will not reference the old array address memory. When building a real-world application, handling state management is super important. So knowing how to create immutable objects (arrays) is super essential.
With Array.from
you can create a shallow* copy of an array, so that the original array will be immutable if you do some operations on the copied array.
const movies = ['love','poetry','drama'];
const moviesClone = Array.from(movies);
movies.push('action');
console.log(movies);
// [ 'love', 'poetry', 'drama', 'action' ]
console.log(moviesClone);
// [ 'love', 'poetry', 'drama' ]
The Array.from
method also (optionally) takes a mapFn
to call on every element on the newly created array. If provided, every value to be added to the array is first passed through this function, and mapFn
's return value is added to the array instead ↓
const movies = ['love','poetry','drama'];
const moviesClone = Array.from(movies, (movie => movie.toUpperCase()));
movies.push('action');
console.log(movies);
// [ 'love', 'poetry', 'drama', 'action' ]
console.log(moviesClone);
//[ 'LOVE', 'POETRY', 'DRAMA' ]
Cloning with Spread Operator
In JavaScript, cloning an array can be done efficiently and succinctly with the use of the spread operator (...
). This is especially useful when you want to create a copy of an array that can be modified without affecting the original array.
const movies = ['love','poetry','drama'];
const moviesClone = [...movies];
movies.push('action');
console.log(movies);
// [ 'love', 'poetry', 'drama', 'action' ]
console.log(moviesClone);
// [ 'love', 'poetry', 'drama' ]
The spread operator takes all elements from the movies
array and "spreads" them into a new array. This technique is not only concise but also very readable. As a result, clonedMovies
is a new array that contains the same elements as movies
, but is independent of it.
🔍. Similar posts
The Simple Way to Run a Long Docker Command in Multiline
14 Jan 2025
How to Hard Reset Your Git Repository to 10 Minutes Ago
04 Sep 2024
How to Easily Generate a Java Project Using Maven Command
04 Sep 2024