Weekly Webtips
Published in

Weekly Webtips

Tech: Avoid Array Mutation in JavaScript

Never have to worry about mutating arrays again with these awesome tips

Avoid Array Mutation in JavaScript

If you are a JavaScript developer like me you won’t be surprised how often array data structure is being used in the code in order to store and manage lists of data. The problem with arrays in JS is that they are easily mutable due to “passing by reference” nature in JS. In addition to that, array immutability can be a challenging problem since developers usually get turned off by confusing syntax or didn’t do it properly. In this article, we will go through some common techniques to help you become familiar with how to prevent array mutation in JS.

Generate Arrays

Array(5).fill(0);
// [0, 0, 0, 0, 0]
Array.from(Array(5), (_, index) => 2 + index);
// [2, 3, 4, 5, 6]

Checking for Array Type

const array = ['a', 'b'];
Array.isArray(array); // true, also works through iframes
array instanceof Array; // true

Shallow Copy / Clone Arrays

1. Spread Operator

const newArray = [...array];

2. Array’s Slice() method

const newArray = array.slice();           // clone whole array
const newArray = array.slice(0); // clone whole array
const newArray = array.slice(start, end); // clone partial array

3. JSON-serializable content

const newArray = JSON.parse(JSON.stringify(array));

Add / Insert

1. Add Item to Array

const array = ['a', 'b'];
const newArray = [...array, 'c'];
// newArray = ['a', 'b', 'c']

2. Add Item At Index

const array = ['a', 'b'];
const targetIdx = 1;
const newArray = [
...arr.slice(0, targetIdx),
'c',
...arr.slice(targetIdx)
];
// newArray = ['a', 'c', 'b']

3. Conditionally Add Item to Array

const array = ['a', 'b'];
const isAdded = false;
const newArray = [
...array,
...(isAdded ? ['d'] : []),
'e'
];
// newArray = ['a', 'b', 'c', 'e']

Delete

1. Delete Last Item from Array

const array = ['a', 'b', 'c'];
const newArray = array.slice(0, array.length - 1);
// newArray = ['a', 'b']

2. Delete Item At Index

const array = ['a', 'b', 'c'];
const targetIdx = 1;
const newArray = array.filter((item, i) => i !== targetIdx);
// newArray = ['a', 'c']

Update

1. Update Item at Index

const array = [{name: 'John'}, {name: 'Katy'}];
const targetIdx = 1;
const newArray = array.map((item, i) => {
return i === targetIdx ? { ...item, name: "Alice" } : item;
});
// newArray = [{name: 'John'}, {name: 'Alice'}];

Sort

const a = [{age: 10}, {age: 20}, {age: 5}];
const sorted = [...a].sort((a: any, b: any) => a.age - b.age, 0);
// sorted = [{age: 5}, {age: 10}, {age: 20}]

Reduce

const a = [{age: 10}, {age: 20}, {age: 5}];
const sum = [...a].reduce((sum, item) => sum + item.age);
// sum = 35

More Useful Array Operations

1. Intersection

const a = ['a', 'b', 'c'];
const b = ['a', 'b', 'd'];
const intersection = a.filter(item => b.includes(item));
// intersection = ['a', 'b']

2. Difference

const a = ['a', 'b', 'c'];
const b = ['a', 'b', 'd'];
const difference = a.filter(item => !b.includes(item));
// difference = ['c']

3. Union / Combine

const a = ['a', 'b', 'c'];
const b = ['a', 'b', 'd'];
const union = a.concat(b);
// union = ['c']

Final Thoughts

With these awesome techniques, you will never make any mistakes of mutating arrays in JS. Feel free to bookmark this page for future references. In the meantime, I’ll continue adding more useful tips and tricks about array immutability with a lot of examples and demonstrations. Stay tuned!

--

--

--

Explore the world of web technologies through a series of tutorials

Recommended from Medium

Write once use everywhere with React Native.

Favorite Node packages & Vue — Early 2020

Create pagination in React using Hooks.

How Chrome Extension simplified part of my tasks

Tech: Why Angular Strict Mode Is a Game Changer

Controlling your PC with mobile browser using Nodejs

React: Update dynamic content dynamically depends on Device Screen sizes

Here are three upcoming changes to JavaScript that you’ll love

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Khoi Bui

Khoi Bui

Front End architect, opensource contributor and investment enthusiast. New content posted every week.

More from Medium

Typescript: Type VS Interface

Roman to Integer in Typescript (again :))

Client Side Gzip Compression using Webpack in React

DI — Dependency Injection