0

Take example below code, splice is used to recover one specific item from Array1 and stored in Popped. Then popped is pushed into array2. However if i delete popped, why array2 becomes undefined even though the value has already been pushed.

let Array1 = [
{id: 1, name: "APPLES"},
{id: 2, name: "ORANGE"},
{id: 3, name: "PEAR"},
{id: 4, name: "MANGO"}];
let array2 = [];

let popped  = Array1.splice(0, 1)
array2.push(popped);
console.log("Array2: ", array2[0][0].name)
document.querySelector("#First").innerHTML = "First: " + array2[0][0].name;
delete popped[0]; //why when we delete popped, value is undefined  ? 
document.querySelector("#Second").innerHTML = "Second: " + array2[0][0].name; // undefined
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
mahen23
  • 720
  • 2
  • 11
  • 24
  • 1
    Because popped and array2[0] are the same array: `array2.push(popped);`: this stores popped in array2[0]. – JB Nizet Aug 15 '19 at 09:44
  • ok how do i bypass this issue ? Any solution ? – mahen23 Aug 15 '19 at 09:46
  • 1
    What exactly is the issue? If you remove something from an array, it's removed from the array. The contrary would be quite an issue. If you don't want something to be deleted, then don't delete it. If you want array2[0] to be a different array from popped, then don't push popped into array2. You can push a **copy** of the array if that's what you want. – JB Nizet Aug 15 '19 at 09:48
  • we can push a copy of popped without deleting the original contents of popped ? How ? – mahen23 Aug 15 '19 at 09:50
  • The way i understands it, the splicing takes place on Array1. Popped is just a temporary storage. Its actually Array1 that physically looses an item. – mahen23 Aug 15 '19 at 09:58
  • Your understanding is wrong. There is no such thing as "a temporary storage". The documentation of splice (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice#Return_value) says that it returns an array. You're storing a reference to that array in another array. Jack's answer shows how to create a copy of an array, i.e. another array that contains references to the same objects as the original one. – JB Nizet Aug 15 '19 at 11:43
  • I may have asked the question wrongly. This was the answer i was looking for: https://stackoverflow.com/questions/36124363/deep-copying-objects-in-angular Also today i learned there was such a thing as deep copy and shallow copy. – mahen23 Aug 15 '19 at 11:57

1 Answers1

2

You should copy popped when you add it to the array, so it's not the reference but rather a new array that is added.

array2.push([...popped]);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79