javascriptarraysarray-splice

How to remove elements from object of arrays


I use an object of arrays and I want to delete a specific value in 1 of the arrays.

let medici= ["Person1","Person2", "Person3", "Person4", "Person5",  "Person6" ];
let giorni = ["Lun", "Mar", "Mer","Gio","Ven"]; let presenti ={};
for  (let giorno of giorni){ presenti[giorno] = medici; }

I obtain:

Gio: ["Person1", "Person2", "Person3", "Person4", "Person5", "Person6"],
  Lun: ["Person1", "Person2", "Person3", "Person4", "Person5", "Person6"],
  Mar: ["Person1", "Person2", "Person3", "Person4", "Person5", "Person6"],
  Mer: ["Person1", "Person2", "Person3", "Person4", "Person5", "Person6"],
  Ven: ["Person1", "Person2", "Person3", "Person4", "Person5", "Person6"]

Now I want to delete specific value in specific array:

giorno="Ven";
nome="Person1";
presenti[giorno].splice(presenti[giorno].indexOf(nome), 1);

It delete the value in all the arrays!!! Not only in the "Ven" one... How can I delete a single one element in a specific array not affecting the other arrays of the object?

Thx


Solution

  • When you build your object all the arrays have the same reference so you will need to slice medici on each object value. Take a look to Copy array by value

    Now you can use method.

    let medici= ["Person1","Person2", "Person3", "Person4", "Person5",  "Person6" ];
    let giorni = ["Lun", "Mar", "Mer","Gio","Ven"]; let presenti ={};
    for  (let giorno of giorni){ presenti[giorno] = medici.slice(); }
    
    let giorno="Ven";
    let nome="Person1";
    
    presenti[giorno].splice(presenti[giorno].indexOf(nome), 1);
    console.log(presenti)