Prevent Array Mutation - Javascript

Kishan Panchal
Jul 23, 2020 · 2 min read

Hi, In this blog I am going to show, How to prevent array mutation.

Here, We have an array of objects countries.

let countries = [
{id: 1, name: "India", image: "thumb10.jpg"},
{id: 2, name: "Africa", image: "thumb11.jpg"},
{id: 3, name: "South Africa", image: "thumb12.jpg"},
{id: 4, name: "Bolivia", image: "thumb13.jpg"}
];

Return specific fields from the array

From the countries array, we want only two fields id and name. So we use the array mapping function to get the desired result.

let output = countries.map(s => ({ id: s.id, name: s.name}));
console.log(countries); // there will be no change in array
console.log(output); // it returns only two feilds in array

What if we have multiple fields in an array object and we want dynamic fields of them. i.e,

let fieldsOfArray = ["id", "name", "image"];
let requiredFields = ["id", "name"];
let output = countries; // assigning the countries array to output.for(const i in output) {
for (const x in fieldsOfArray) {
if(!fieldsOfArray.includes(requiredFields[x])) {
// deleting column/field from output
delete output[i][fieldsOfArray[x]];
}
}
}
console.log(countries); // [{id: 1, name: "India"}, {id: 2 ....}];
console.log(outpput); // [{id: 1, name: "India"}, {id: 2 ....}];

deleting fields from the assigned variable will delete same fields from the original array. So, we need to make a copy of the original array and then assign it to another variable to prevent this mutation of array.
There are few techniques to make a copy of array, like using the slice() method or using spread notation (...) , i.e.,

let output = countries.slice(); // or
let output = [...countries];

Using the slice() or spread notation (...) will make the shallow copy of the array. “shallow” the word says itself and it won’t work in every case as like we have an example above.

That was the realtime issue I have faced once in my project and I have tried many methods to copy the array but It was modifying the original array.
So, here I came up with a solution from which we can make a copy of the array to prevent modifying the original array.

// make a copy of original array
function copy(obj) {
var output, v, key;
output = Array.isArray(obj) ? [] : {};
for (key in obj) {
v = obj[key];
output[key] = (typeof v === "object") ? copy(v) : v;
}
return output;
}
let countries = [
{id: 1, name: "India", image: "thumb10.jpg"},
{id: 2, name: "Africa", image: "thumb11.jpg"},
{id: 3, name: "South Africa", image: "thumb12.jpg"},
{id: 4, name: "Bolivia", image: "thumb13.jpg"}
];
let fieldsOfArray = ["id", "name", "image"];
let requiredFields = ["id", "name"];
console.log('countries before delete', countries);// let output = countries;
// let output = countries.slice();
let output = [...countries];
// let output = copy(countries);
for(const i in output) {
for (const x in fieldsOfArray) {
if(!fieldsOfArray.includes(requiredFields[x])) {
// deleting column/field from output
delete output[i][fieldsOfArray[x]];
}
}
}
console.log('countries data after delete process', countries);

You can uncomment the different methods of copying an array in the above example and run the code to check the difference between all methods to copy the array.

Visit for amazing stuff.

Happy Coding :)

The Startup

Get smarter at building your thing. Join The Startup’s +724K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface.

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox.

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic.

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