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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

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