0

I am creating an array in a project on NodeJs. When I send the array to a function, it changes the main array even if I assign the data to a temporary variable and make changes in that temporary variable. But I don't want any changes to the main array.

function abc(data) {
  console.log("1. " + data.text);
  var tempss = data;
  console.log("2. " + tempss.text);
  tempss.text = 20;
  console.log("3. " + data.text);
  console.log("4. " + tempss.text);
}
let a = new Array();
a.text = 3;
abc(a);
console.log("5. " + a.text);

Result:

1. 3
2. 3
3. 20
4. 20
5. 20

What I want to do:

1. 3
2. 3
3. 3
4. 20
5. 3
Ele
  • 33,468
  • 7
  • 37
  • 75
huso
  • 9
  • 2
  • Does this answer your question? [Copy array by value](https://stackoverflow.com/questions/7486085/copy-array-by-value) – Miss Skooter May 20 '23 at 20:55
  • You're looking for deep copy technique in Javascript. I wonder why you use an array to add properties like `.text`, Why don't you use just an object instead? – Lucas David Ferrero May 20 '23 at 21:13
  • You should use `structuredClone()` to deep copy the array. I recommend you this article: https://developer.mozilla.org/en-US/docs/Glossary/Deep_copy – Lucas David Ferrero May 20 '23 at 21:26

1 Answers1

-2

You can copy the array instead of assigning its value, so the other variable will be only similar, but not the same. This could be done in many different manners, I will share here an example with the spread operator of ...

let a = [1, 2, 3, 4, 5];
let b = [...a];

b[2] = 345;
console.log(b);
console.log(a);
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • Your answer is correct, but for me personally, this question is a very clear duplicate and should be closed as such. Further, The duplicates contain very thorough answers that provide significantly more information than your answer (your answer is also covered there) so to me this smells like rep farming and you didn't add anything new in your answer. [this meta post](https://meta.stackoverflow.com/a/352195/13927534) explains my opinion well – Miss Skooter May 21 '23 at 06:43