0

Screenshot of the Output

This is a simplified version of the problem =>

const z = [
  [1, 2, 3, 4, 5]
];

console.log(z);

z[0].splice(1, 1);

console.log(z);

Both Console logs output : Array [ (5) […] ] 0: Array(4) [ 1, 3, 4, … ] ​length: 1

How is splice affecting the first console log? ​

I was making an algorithm then I noticed that even before calling the splicing function my original array which had thousands of items was getting affected meaning that the "History" or "Log" array that I was trying to form always had the same spliced version of the array that i later on tried splicing.

  • 1
    The first log shows `[1, 2, 3, 4, 5]` as expected. You'll need to provide more of your working code. – skyline3000 Jan 26 '23 at 16:08
  • 2
    See [Why does javascript object show different values in console in Chrome, Firefox, Safari?](https://stackoverflow.com/questions/8249136/why-does-javascript-object-show-different-values-in-console-in-chrome-firefox). – jarmod Jan 26 '23 at 16:11
  • Ideas to work around this: [What gets logged in the console when you’re mutating objects?](https://www.freecodecamp.org/news/mutating-objects-what-will-be-logged-in-the-console-ffb24e241e07/) – jarmod Jan 26 '23 at 16:20

1 Answers1

-3

JavaScript's splice() method modifies the original array, meaning that it directly alters the array on which it is called. This is different from some other methods, such as slice(), which create and returns a new array without modifying the original.

const z = [
  [1, 2, 3, 4, 5]
];

console.log(z);
//line below will affect the original array because array is 
// refference in js
// z[0].splice(1, 1);

//instaed make a new deep copy of your variable z
const z2 = JSON.parse(JSON.stringify(z));

//now make the required changes to z2
z2[0].splice(1, 1);

console.log(z2);
Ravi S. Singh
  • 617
  • 8
  • 15