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);