javascript

5 ways to copy an Array in JavaScript


In this article you learn 5 ways to copy an Array in JavaScript, A bulk of the beauty of JavaScript has to lie in its ability to let us do one thing in several ways, using several means. It’s a typical exemplification of the saying;
‘There’s more than one way to skin a cat ’.

Arrays in JavaScript by default are reference values. As the name implies, they simply refer to the actual values and are not the actual values themselves. Due to this, using the assignment operator (=) to copy arrays will only yield a reference to the original array and not the values.

5 ways to copy an array in JavaScript

1. Spread Operators

Symbolic in the introduction of Es6, spread operators are a cool and simple way to clone arrays.

let clubs = ['Chelsea', 'Liverpool', 'Mancity', 'Real Madrid']
console.log(clubs)

//Create a clone Es6 way
let clonedClubs = [...clubs]
console.log(clonedClubs)

2. for() loops

Pretty much not trendy; it however still gets the job done.

let clubs = ['Chelsea', 'Liverpool', 'Mancity', 'Real Madrid']
clonedClubs = [];
for (i = 0; i < clubs.length; i++) {
  clonedClubs[i] = clubs[i];
}
console.log(clonedClubs)

3. Array map()

let clubs = ['Chelsea', 'Liverpool', 'Mancity', 'Real Madrid']
cloning = (i) => i;

clonedClubs = clubs.map(cloning)
console.log(clonedClubs)

4. Array filter()

let clubs = ['Chelsea', 'Liverpool', 'Mancity', 'Real Madrid']

clonedClubs = clubs.filter(() => true);
console.log(clonedClubs)

5. Array slice()

let clubs = ['Chelsea', 'Liverpool', 'Mancity', 'Real Madrid']

clonedClubs = clubs.slice();
console.log(clonedClubs)

Conclusion

Making reference to the statement earlier on, this isn’t an exhaustive list on how to go about cloning arrays. You could find more ways by trying out multiple methods.


Share on social media

//