Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my original array get spliced if I splice the cloned array in JavaScript?

I have the following code:

 var coords = [
     {lat: 39.57904, lng: -8.98094, type: "a"}, // A
     {lat: 39.55436, lng: -8.95493, type: "b"}, // B
     {lat: 39.56634, lng: -8.95836, type: "c"} // C
 ];

 var travelingOptions = [];

 getAllTravelingOptions();

 function getAllTravelingOptions(){
     coords.forEach((point, pos) => {
         let c = coords;
         delete c[pos];
         console.log(c);
         console.log(coords);
     });
 }

Why is it that variable c and coords are always the same? If I delete on c, it mirrors the action on coords. Is this a normal behavior?

like image 896
rafaelmorais Avatar asked Nov 22 '25 09:11

rafaelmorais


2 Answers

Because of the assignment of c, you get the reference of the array coords.

Any change of coords does effect c, until a new value is assigned to c.

If you make a copy of the array with Array.slice, you get a new array but with the same reference of the objects. When changing one object inside, you are changing the same object with the same reference in c.

var coords = [
         {lat: 39.57904, lng: -8.98094, type: "a"}, // A
         {lat: 39.55436, lng: -8.95493, type: "b"}, // B
         {lat: 39.56634, lng: -8.95836, type: "c"} // C
     ],
     c = coords.slice();

console.log(c);
coords[1].type = 'foo';
console.log(c);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 60
Nina Scholz Avatar answered Nov 24 '25 01:11

Nina Scholz


Assignment does not clone array it only creates reference to the orginal object/array. You can use Array.prototype.slice() to make a shallow copy:

let c = coords.slice();
like image 40
madox2 Avatar answered Nov 23 '25 23:11

madox2