Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for How to Avoid Array Mutation
Helder Burato Berto
Helder Burato Berto

Posted on • Edited on • Originally published athelderburato.com

     

How to Avoid Array Mutation

On this article, I'll focus on showing how to add, edit and remove items in an array causing mutation and non-mutation ways.

One thing we need to keep in mind when writing code avoiding mutation is to return a new reference to the data after the update.

It's a common approach when working with functional programming and if you want to understand some concepts of functional programming I recommend you read thisarticle I wrote some time ago.

Why Avoid Mutation

When you work with immutable data you can have some positive impacts like the following:

  • Tracking data without mutation is much better;
  • Immutable states help you implement unidirectional data flow that helps you handle data;

I really recommend you read thisarticle go deeper into why avoid mutation.

Causing Mutation

Causing Mutation

The following steps will cause mutation into the array adding, removing and editing elements fromfamily.

To show an example of mutating, we'll use the following array:

constheroesMutate=['Spider-man','Thor','Hulk','Iron Man'];console.log(heroesMutate);// => ["Spider-man", "Thor", "Hulk", "Iron Man"]
Enter fullscreen modeExit fullscreen mode

Including in Array

Methods that will be used:

See the following use-case examples for these methods:

heroesMutate.push('Captain Marvel');console.log(heroesMutate);// => ["Spider-man", "Thor", "Hulk", "Iron Man", "Captain Marvel"]heroesMutate.unshift('Deadpool');console.log(heroesMutate);// => ["Deadpool", "Spider-man", "Thor", "Hulk", "Iron Man", "Captain Marvel"]heroesMutate.splice(2,0,'Black Panther');console.log(heroesMutate);// => ["Deadpool", "Spider-man", "Black Panther", "Thor", "Hulk", "Iron Man", "Captain Marvel"]
Enter fullscreen modeExit fullscreen mode

Editing the Array

The following case will find index for the element we want to edit and set value to the found index:

constindexDeadpool=heroesMutate.indexOf('Deadpool');heroesMutate[indexDeadpool]='Wolverine';console.log(heroesMutate);// => ["Wolverine", "Spider-man", "Black Panther", "Thor", "Hulk", "Iron Man", "Captain Marvel"]
Enter fullscreen modeExit fullscreen mode

Removing in the Array

Methods that will be used:

See the following use-case examples for these methods:

heroesMutate.pop();console.log(heroesMutate);// => ["Wolverine", "Spider-man", "Black Panther", "Thor", "Hulk", "Iron Man"]heroesMutate.shift();console.log(heroesMutate);// => ["Spider-man", "Black Panther", "Thor", "Hulk", "Iron Man"]heroesMutate.splice(1,1);console.log(heroesMutate);// => ["Spider-man", "Thor", "Hulk", "Iron Man"]
Enter fullscreen modeExit fullscreen mode

Avoiding Mutation

Avoiding Mutation

In this topic, we'll add, remove and edit, avoiding mutations.

Methods that will be used:

See the following use-cases:

constvillains=['Loki','Thanos','Venom','Abomination'];
Enter fullscreen modeExit fullscreen mode

Including in the Array

Add to the end of array:

constnewVillains=villains.concat('Juggernaut');constnewVillains2=[...newVillains,'Magneto'];constnewVillains3=['Red Skull',...newVillains2];console.log(villains);// => ["Loki", "Thanos", "Venom", "Abomination"]console.log(newVillains);// => ["Loki", "Thanos", "Venom", "Abomination", "Juggernaut"]console.log(newVillains2);// => ["Loki", "Thanos", "Venom", "Abomination", "Juggernaut", "Magneto"]console.log(newVillains3);// => ["Red Skull", "Loki", "Thanos", "Venom", "Abomination", "Juggernaut", "Magneto"]
Enter fullscreen modeExit fullscreen mode

In the following example we'll addUltron afterThanos in the array:

constnewVillains=[...villains.slice(0,2),'Ultron',...villains.slice(2,villains.length)];console.log(villains);// => ["Loki", "Thanos", "Venom", "Abomination"]console.log(newVillains);// => ["Loki", "Thanos", "Ultron", "Venom", "Abomination"]
Enter fullscreen modeExit fullscreen mode

Editing the Array

In the following example we'll editVenom toGalactus:

constindexVenom=villains.indexOf('Venom');constnewVillains=[...villains.slice(0,indexVenom),'Galactus',...villains.slice(indexVenom+1)];constnewVillains2=newVillains.map(v=>v==='Abomination'?'Ultron':v);console.log(villains);// => ["Loki", "Thanos", "Venom", "Abomination"]console.log(newVillains);// => ["Loki", "Thanos", "Galactus", "Abomination"]console.log(newVillains2);// => ["Loki", "Thanos", "Galactus", "Ultron"]
Enter fullscreen modeExit fullscreen mode

Removing in the Array

In the following example we'll removeThanos from the array:

constindexThanos=villains.indexOf('Thanos');constnewVillains=[...villains.slice(0,indexHelder),...villains.slice(indexHelder+1)];constnewVillains2=newVillains.filter(v=>v!=='Thanos');console.log(villains);// => ["Loki", "Thanos", "Venom", "Abomination"]console.log(newVillains);// => ["Loki", "Venom", "Abomination"]console.log(newVillains2);// => ["Loki", "Abomination"]
Enter fullscreen modeExit fullscreen mode

See that in all the examples that we developed above, a new instance of the array was created, thus avoiding the mutation of the initially defined arrays.


Wrapping Up

Avoiding mutations is a safe and one-way path.

When you realize that you're writing code observing this type of detail, believe me, you will be writing better, secure code and avoiding possible bugs due to mutation.

Feel free to share your feedback and experience in the comments.

Enjoy programming! ✨

References

Array - JavaScript | MDN;
Marvel Teams, Groups, Squads, & Alliances;

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software Engineer who loves to craft challenging projects and share knowledge with people.
  • Location
    Portugal
  • Work
    Senior Software Engineer at PagerDuty
  • Joined

More fromHelder Burato Berto

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp