DEV Community

Cover image for 1 line of code: How to shallow clone an Array
Martin Krause
Martin Krause

Posted on • Edited on

1 line of code: How to shallow clone an Array

const shallowClone = arr => arr.slice(0); 
Enter fullscreen mode Exit fullscreen mode

Creates a shallow-copied clone of the provided array. Since it's a shallow copy, nested objects or arrays will be copied by reference, not duplicated.


The repository & npm package

You can find the all the utility functions from this series at github.com/martinkr/onelinecode
The library is also published to npm as @onelinecode for your convenience.

The code and the npm package will be updated every time I publish a new article.


Follow me on Twitter: @martinkr and consider to buy me a coffee

Photo by zoo_monkey on Unsplash


Top comments (6)

Collapse
 
martinkr profile image
Martin Krause • Edited

Thank you for sharing! Yes, there are multiple other ways to shallow clone an array in javascript. As so often in programming, at one point you have to choose ;)

I run benchmarks before posting and .slice(0) was the fastest on my machine. The perf.link you posted comes up with 76,280 ops/s for .slice(0) and 70,030 ops/s for spread - but I think the difference is negligible. Depending on the engine and the environment it can easily be the other way around.

Cheers!

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

I am enjoying this series too, particular attention to detail in the comments and bencharks.

I do always question the importance and benchmarks because a blink of an eye is similar to a slower blink of an eye but we are where we are in the world of JavaScript, what's always amazing is that the older ways are generally faster across the board, but I would still put convenience of writing over customer experience if the experience was marginally affected, that's just me, call me the bad guy 🤪

Collapse
 
martinkr profile image
Martin Krause

From my perspective, the benchamrkings are super interesting because you would expect the "new", modern functions being performance optimised (otherwise, why would you implement them?) but often, as you said, they are not. At least not yet.

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

Not yet indeed, I remember the window.Proxy was introduced in Chrome for example, lots of people said, don't use it, its slow and hard for the engine to optimize, if not impossible. but then 6 months later I stumbled upon a blog by the lady who did the optimization in V8 and get it running quite a lot faster. Sadly I can't remember by how much but, it's always stuck in my mind, I'm okay with Proxy these days

Collapse
 
johnnyuft profile image
Johnny

I read: shadow clone (jutsu). My bad.

Collapse
 
ben profile image
Ben Halpern

Keep up the series!