DEV Community

P Santosh Kumar
P Santosh Kumar

Posted on

Ways to clone a array and is deep cloning important ?

let arr = [{a:1,b:2},{a:2,b:4},{a:3,b:6}],
    clone1,clone2,clone3,clone4,clone5,clone6;
clone1 = arr => [...arr];
clone2 = arr => arr.slice(0);
clone3 = arr => Array.from(arr);
clone4 = arr => arr.map(x => x);
clone5 = arr => arr.concat([]);
clone6 = arr => JSON.parse(JSON.stringify(arr));


let spreadArr = clone1(arr);
let sliceArr = clone2(arr);
let fromArr = clone3(arr);
let mapArr = clone4(arr);
let concat = clone5(arr);
let deepclone = clone6(arr);


console.log('spreadArr',spreadArr);
console.log('sliceArr',sliceArr);
console.log('fromArr',fromArr);
console.log('mapArr',mapArr);
console.log('concat',concat);
console.log('deepclone',deepclone);


arr = arr.map(x => x.a = x.a*2);


// if I modify arr it will reflect to all other array
// except the deepclone array ( json.parse(json.stringify(arr)))

// Be careful on type of cloning you want to choose when working with array // of objects 


console.log('After map operation');


console.log('spreadArr',spreadArr);
console.log('sliceArr',sliceArr);
console.log('fromArr',fromArr);
console.log('mapArr',mapArr);
console.log('concat',concat);
console.log('deepclone',deepclone);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)