I have an array I want to use as base array of my work, and each time a unction calls I want it to be cloned to prevent changing the base one, but it doesn't work I don't know why and I tried all other solutions else where
this is my code:
const baseArray = [
{
english: {
name: "test1 english",
description: "test1 english"
},
spanish: {
name: "test1 spanish",
description: "test1 spanish"
}
}
];
function removeSpanish() {
// showing base array before work
console.log(baseArray); // expected to log the baseArray, but logs the edited array
// cloning the array
var result = [...baseArray];
// checking if passed by value or passed by reference
console.log(result[0] === baseArray[0]); // expected to log false, but it logs true
// removing other language details from each collection
result.map(collection => {
delete collection['spanish'];
return collection;
});
// showing base array after work
console.log(baseArray); // expected to log the baseArray, but logs the edited array
return result;
}
export { find };
and what surprises me is that even the first
console.log(baseArray)
shows the edited one.
and the
console.log(result[0] === baseArray[0]);
logs true so they are passed by refference
i also tried these 2 other approaches but none of them worked
var result = baseArray.splice();
var result = Array.from(baseArray);
NOTE: i use this in react and it will be excuted each time a state changes, I don't know if it causes the problem