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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay