DEV Community

Heru Hartanto
Heru Hartanto

Posted on

2 1

How to duplicate array

If you run following script, something weird will happen, can you tell me ?

    const arrayA = [1,2,3]
    const duplicate = arrayA 
    duplicate.push(4)
    console.log(duplicate,arrayA)
Enter fullscreen mode Exit fullscreen mode

output for that example will be something like this

[1, 2, 3, 4] [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Yes the value from duplicate array is correct as we expected, but why arrayA value is changed ?

this happen because we did assignment duplicate = arrayA and assignment in array is working as reference, so when we try to copy an array using assignment what happen actually is new variable will copy reference to original array and not value of original array.

to handle this problem you can use spread operator to clone arrayA, spread operator is a new feature that introduce in ES6,

    const arrayA = [1,2,3]
    const duplicate = [...arrayA] 
    duplicate.push(4)
    console.log(duplicate,arrayA)
Enter fullscreen mode Exit fullscreen mode

output for that example

[1, 2, 3, 4] [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
madrafj profile image
Ahmad Rafsanjani

I wonder how people do it before spread operator exists ?..

Collapse
 
elukuro profile image
Heru Hartanto

I did this 😆

const a =[1,2,3]
const b = a.slice()
b.push(4)
console.log(a,b)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
madrafj profile image
Ahmad Rafsanjani

Aah..got it.. thanx

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay