Steven Hsu
Steven Hsu

Reputation: 183

Javascript - Modifying two arrays in while loop, both arrays retaining second value

I have an array data, that contains a nodeData object, which contains an id

I make 2 copies of the array:

    const dropAboveData = data.slice();
    const dropBelowData = data.slice();

and then I try to modify both copies of my 2 copied arrays differently

    for(let i = 0; i<data.length; i++){
        dropAboveData[i].nodeData.id = -1;
        dropBelowData[i].nodeData.id = -2;
    }

So for example if each record in data had data[i].nodeData.id = 0, at the end i would expect dropAboveData to contain all -1 for id, and dropBelowData to contain all -2 for id.

But instead it seems like data, dropAboveData, and dropBelowData all become arrays filled with -2.

Why is this happening? I though slice() makes a copy of the array so that i'm not accessing the same object?

Upvotes: 0

Views: 46

Answers (2)

Emeeus
Emeeus

Reputation: 5250

Slice makes a shallow copy

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

You could copy an array of objects like this:

var data = [{
  'a': '0'
}, {
  'b': '1'
}, {
  'c': '2'
}]
dropAboveData = []
dropBelowData = []

data.map(o => {
  dropAboveData.push(JSON.parse(JSON.stringify(o)));
  dropBelowData.push(JSON.parse(JSON.stringify(o)));
});

dropAboveData[0] = 1; //<-- modify only dropAboveData
dropAboveData[1].b = 99;//<-- modify only dropAboveData

console.log(dropAboveData)
console.log(dropBelowData)

Upvotes: 1

Steven Hsu
Steven Hsu

Reputation: 183

as charieftl pointed out i was not copying the objects in my array (nodeData objects).

    const dropAboveData = data.map(item => item.nodeData.id = -1);
    const dropBelowData = data.map(item => item.nodeData.id = -2);

did what I wanted.

Upvotes: 0

Related Questions