DEV Community

Cover image for 1 line of code: How to shallow clone an Array
martin krause
martin krause

Posted on • Updated 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


Discussion (4)

Collapse
lukeshiru profile image
LUKESHIRU

You can also do:

const shallowClone = array => [...array];
Enter fullscreen mode Exit fullscreen mode

Which can be faster

Cheers!

Collapse
martinkr profile image
martin krause Author • Edited on

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
johnnyuft profile image
Johnny

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

Collapse
ben profile image
Ben Halpern

Keep up the series!