Reputation: 521
My understandig was that Array.filter creates a clone of the object, but in the example below both type1 and type1a obviously share the some data.
let initial = [
{id: 1, type: 1, name: "first", count:0},
{id: 2, type: 2, name: "second", count:0},
{id: 3, type: 1, name: "third", count:0},
{id: 4, type: 2, name: "fourth", count:0},
];
let type1 = initial.filter((item)=>item.type===1);
let type1a = initial.filter((item)=>item.type===1);
type1[0].count = 2;
console.log(type1a[0].count);
Results:
Expected result: 0
Got: 2
What am I missing?
I have tried adding the spread operator in both assignemnet but the result is the same :(
Thanks to @Thomas for the answer.
For your reference, the correct code is:
let initial = [
{ id: 1, type: 1, name: "first", count: 0 },
{ id: 2, type: 2, name: "second", count: 0 },
{ id: 3, type: 1, name: "third", count: 0 },
{ id: 4, type: 2, name: "fourth", count: 0 }
];
// let type1 = initial.filter(item => item.type === 1);
let type1 = [];
initial.forEach((item)=>{
if(item.type === 1)
type1.push(JSON.parse(JSON.stringify(item))
)
})
// let type1a = initial.filter(item => item.type === 1);
let type1a = [];
initial.forEach((item)=>{
if(item.type === 1)
type1a.push(JSON.parse(JSON.stringify(item))
)
})
type1[0].count = 2;
console.log(type1[0].count);
console.log(type1a[0].count);
Upvotes: 10
Views: 13611
Reputation: 182008
You get a brand new array, but the array contains references to objects. The references are copied, but not the objects they refer to. This is a so-called "shallow" copy.
To make a "deep" copy that is entirely independent, see this question.
Upvotes: 17