DEV Community

loading...
Cover image for 6 Use Cases of Spread with Array in JavaScript

6 Use Cases of Spread with Array in JavaScript

samanthaming profile image Samantha Ming Originally published at samanthaming.com Updated on ・5 min read

Alt Text

Here are 6 ways to use the Spread operator with Array in JavaScript. You can use it to merge or clone an array. Or use it to convert iterables to an array.

// Merge Array
[...array1, ...array2]

// Clone Array
[...array]

// Sting → Array
[...'string']

// Set  → Array
[...new Set([1,2,3])]

// Node List → Array
[...nodeList]

// Arguments → Array
[...arguments]

Understanding Spread

MDN: Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

Clear as mud right 😂 Spread took me a long time to understand. So let me try to explain with 2 analogies that helped me. Hopefully, it can also help you 🤞

Spread is like Russian Dolls

The spread syntax takes your array and expands it into elements. Imagine your array is like those Russian Dolls. When you call the spread syntax on it, it will take the nested individual doll out and lay it out in its own individual pieces.

Credit: Wikipedia

Spread is like an Eraser

If the Russian Dolls analogy didn't help and Spread is still muddy for you 😵 In that case, just think of the ... syntax as an eraser that removes the brackets of the array 😂

[
  ...[1, 2, 3] // 👈 The dots erases the brackets
]

/*  Becoming this: */
[
  1, 2, 3 // 👈 "Erased"
]

Array Manipulation

The best thing about the Spread syntax is to use it for array manipulation 👏

1. Use Spread for Merging Array

Let's say we have 2 arrays.

const array1 = [1, 2, 3];

const array2 = [4, 5, 6];

Let's see what happens when we try to merge the array without the spread syntax.

const attemptToMerge = [array1, array];

attemptToMerge;
// [ [1, 2, 3],  [4, 5, 6] ] 👈 😱

👆 When you try to merge an array without the spread syntax, you wind up with a nested or multi-dimensional array.

So let's use the Spread syntax to "erase" the brackets.

const mergedArray = [
  ...array1,
  ...array2
];

mergedArray;
// [ 1, 2, 3, 4, 5, 6 ]

2. Clone Array

Cloning array in JavaScript isn't as straight forward. So let's see it done in 2 paths - the wrong way and the right way 🛣

Cloning Array the Wrong Way

In JavaScript, arrays are reference types, so you can't just create a new copy of an array using =. Let's see what problem happens if we try to do it that way.

const original = ['zero', 'one'];
const newArray = original;

original; // ['zero', 'one']
newArray; // ['zero', 'one']

👆So everything looks okay so far, but let's see what happens if we change the element.

newArray[1] = '💩';

newArray;
// ['zero', '💩']

original;
// ['zero', '💩']  👈 😱 Our original array is affected

OH yikes 😱 Changing the newArray will mutate the original array 👎

Think of references as addresses. When we create a copy of an array using =, we've only copied the address. We have NOT copied the underlying array, which is what we want. To do that, we need to copy the array at a new address. That way, when we make changes to our new array, it won't affect the original array -- because they're at different addresses.

Cloning Array the Right Way

const original = ['zero', 'one'];
const newArray = [...original];

original; // ['zero', 'one']
newArray; // ['zero', 'one']

So if we did this correctly, our original array shouldn't be affected if we changed the newArray. Alright, let's give this a try 💪

newArray[1] = '💩';

newArray;
// ['zero', '💩']

original;
// ['zero', 'one']  ✅ original array is NOT affected

Iterables to Array

With Spread, converting different data types to an Array has never been easier 👏

3. String to Array

When we spread a string, it will return an array of individual substrings.

const string = 'hi';

const array = [...string];

array;
// [ 'h' , 'i' ]

4. Set to Array

Let's create a new set object:

const set = new Set([1, 2, 3]);

set;
// Set(3) {1, 2, 3}

Using Spread, we can convert the set into an array:

const array = [...set];

array;
// [1, 2, 3]

5. Node List to Array

Let's create a node list:

const nodeList = document.querySelectorAll('p');

nodeList;
// [p, p, p]

Now we can use Spread to convert our node list into an array:

const array = [...nodeList];

array;

6. Arguments to Array

Before we begin, let's take some time to understand what the arguments objects is.

MDN: arguments is an Array-like object accessible inside functions that contains the values of the arguments passed to that function.

👆 Notice the key there, array-like -- So it looks like an array, but it isn't (oh JS, always making things so fun for us to understand you 😅). The benefit of converting the arguments object to an array means we have access to all the awesome array methods (ie. map, filter, find) 👍

function names() {
  arguments;
  // Arguments(4)['samantha', 'sam']

  arguments.map(name => `hi ${name}`);
  // ❌ TypeError: arguments.map is not a function
}

names('samantha', 'sam');

Alright, let's convert our arguments into an array so we can apply array methods on it 🙌

function names() {
  const argumentsArray = [...arguments];

  argumentsArray.map(name => `hi ${name}`);
  // ✅ ['hi samantha', 'hi sam']
}

names('samantha', 'sam');

Community Input

  • @harmleprinze: Split will give more options, considering it takes in separator and limit

  • @mohammed_mamoun_98: If you merged two arrays without spread it's gonna be two-dimensional array but flat make it one dimension so it's more effective I guess. You can try it

  • @bukazoltan: The min() and max() method cannot take an array as an input, so spreading it can solve that problem too... It saved me a lot of headaches.

array = [1, 2, 3, 4, 5];
var minimum = Math.min(...array);
var maximum = Math.max(...array);

Resources


Thanks for reading ❤
Say Hello! Instagram | Twitter | SamanthaMing.com

Discussion (24)

pic
Editor guide
Collapse
huncyrus profile image
huncyrus

Side note: The new Set() and the spread operator could be quite dangerous, worth to check out the behaviour: it is really copy by value or just by reference... (might be handy this small detail when ppl workin' on large datasets)

Collapse
samanthaming profile image
Samantha Ming Author

But wouldn't spread be creating a true new copy? -- do you mind expanding your thought, might be something helpful to include in my code notes 😵

Collapse
penge profile image
Pavel Bucka

Try this:

const set = new Set([{ id: 1, color: "blue" }, { id: 2, color: "red" }, { id: 3, color: "green" }]);

const arr = [...set];
arr[0].color = "purple";

console.log(set); // check the first entry
// or set.values().next().value.color

The conclusion is: spreading results in a shallow copy.

Source: stackoverflow.com/questions/500511...

That means, copying primitive values turns fine. What you can do in case of objects copy, is to make a copy of those underlying objects:

const arr2 = [...set].map(item => Object.assign({}, item));
arr2[0].color = "yellow";

console.log(set); // check the first entry

But how about nested objects? Try this:

const set = new Set([{ id: 1, color: "blue", details: { weight: 10 } }, { id: 2, color: "red", details: { weight: 20 } }, { id: 3, color: "green", details: { weight: 30 } }]);

const arr2 = [...set].map(item => Object.assign({}, item));
arr2[0].details.weight = 12;

console.log(set); // check the first entry

The conclusion is: Object.assign copies property values only (not a deep copy).

Source: developer.mozilla.org/en-US/docs/W...


Conclusions:

- spreading results in a shallow copy
- Object.assign copies property values only (not a deep copy)

Collapse
penge profile image
Pavel Bucka

I loved reading this article!! No bs, right to the point. And great analogies with Russian dolls or Eraser! I didn't understand that mud from MDN as well :D
Although it is a familiar topic to me, I found it entertaining and interesting enough to read it till the end. Great work! :-)

Collapse
samanthaming profile image
Samantha Ming Author

Who said learning programming can't be entertaining or interesting 😆 Thanks so much for the positive feedback! Entertain-learning (yup, I just TM that 😂) is my goal for all my code notes now! 🙌

Collapse
wrldwzrd89 profile image
Eric Ahnell

Fun! I can see a somewhat unusual use for this: in web games, you need arrays for various reasons. It’s usually more efficient to store only one dimension, even if the data isn’t, and simulate a multidimensional array. Spread gives a convenient way to make the simulation less annoying for consumers, from the perspective of a JS library.

Collapse
samanthaming profile image
Samantha Ming Author

Interesting, thanks for sharing! 🎮

Collapse
pony profile image
Pony

Nice post,
Thanks, Samantha

Collapse
samanthaming profile image
Samantha Ming Author

Thank for reading my code notes 😄

Collapse
bukazoltan profile image
bukazoltan • Edited

Lovely useful aericle.
I also often use it to get min and max of an array 😊

Collapse
samanthaming profile image
Samantha Ming Author

min and max? please say more! 🤩

Collapse
bukazoltan profile image
bukazoltan • Edited

Well, the min() and max() method cannot take an array as an input, so spreading it can solve that problem too... It saved me a lot of headaches.

array = [1, 2, 3, 4, 5];
var minimum = Math.min(...array);
var maximum = Math.max(...array);
Thread Thread
samanthaming profile image
Samantha Ming Author

Ah yes! that's a fantastic use case! let me add it to my notes, thanks for sharing 💪

Collapse
mustafaaljassim profile image
Eng_Mustafa

Samantha! You just make everything simple and easy to understand. Please try to share more content. I have been addicted to yours 😭

Collapse
samanthaming profile image
Samantha Ming Author

Thank you so much!!! Will dooo 😊😊😊

Collapse
dotorimook profile image
dotorimook

Nice to read! Thank you!

Collapse
samanthaming profile image
Samantha Ming Author

Yay! thank you for reading 🙂

Collapse
tradecoder profile image
Mamun

Good explanation.

Collapse
samanthaming profile image
Samantha Ming Author

thanks, glad you find it helpful 👏

Collapse
penandpapers profile image
PenAndPapers

I dont use spread operators much but now that I have a better understanding on how it work i'd probably use them more. Thanks for sharing this.

Collapse
samanthaming profile image
Samantha Ming Author

great! that's the goal of the post. Spread is super awesome, but it can be tricky to understand. So glad it makes more sense to you and you're encouraged to use it more 👏

Collapse
bernardbaker profile image
Bernard Baker

I like reading your articles 🤸.

Collapse
samanthaming profile image
Samantha Ming Author

Awesome happy to hear that! glad you find them helpful 👏

Collapse
glaydson profile image
Glaydson V Sousa

Thank you for sharing this, now I think I understand spread operator!