Arrays are Reference Types
- Copying a Value type
let value = 3;
let valueCopy = value; // create copy
console.log(valueCopy); // 3
// Change valueCopy
valueCopy = 100
console.log(valueCopy); // 100
// ✅ Original NOT affected
console.log(value); // 3
- Copying a Reference type
let array = [1,2,3];
let arrayCopy = array; // create copy
console.log(arrayCopy); // [1,2,3];
// Change 1st element of the array
arrayCopy[0] = '👻';
console.log(arrayCopy); // [ '👻', 2, 3 ]
// ❌Original got affected
console.log(array); // [ '👻', 2, 3 ]
Solutions:
-
let arrayCopy = [...array]
(Shallow copy) let copyArr = arr.slice()
-
let copyArr = Object.assign([], arr)
✅Works for one-dimensioned array.
❌Won't work for nested array.
let arrayCopy = JSON.parse(JSON.stringify(nestedArray));
(Deep copy)
✅ Only work with Number and String and Object literal without function or Symbol properties.
❌ Function or Symbol properties ( values not compatible with JSON )deepclone
✅work with all types, function and Symbol are copied by reference.
const lodashClonedeep = require("lodash.clonedeep");
const arrOfFunction = [() => 2, {
test: () => 3,
}, Symbol('4')];
// deepClone copy by refence function and Symbol
console.log(lodashClonedeep(arrOfFunction));
// JSON replace function with null and function in object with undefined
console.log(JSON.parse(JSON.stringify(arrOfFunction)));
// function and symbol are copied by reference in deepClone
console.log(lodashClonedeep(arrOfFunction)[0] === lodashClonedeep(arrOfFunction)[0]);
console.log(lodashClonedeep(arrOfFunction)[2] === lodashClonedeep(arrOfFunction)[2]);
- Using Recursion
const clone = (items) => items.map(item => Array.isArray(item) ? clone(item) : item);