Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

213
Vistas
Why are all of the arrays deleting an element in this set instead of the one being referenced?

My code:

uniformPieces3 = ['company1_hat', 'company1_glasses', 'company2_hat']
uniformSet3 = ['hat', 'glasses']


f1 = function(uniformSet, uniformPieces) {

uniformPieces.sort();
let arr1 = []
for (i = 0; i < uniformPieces.length; i++){
    arr1[i] = uniformPieces[i].substr(0, uniformPieces[i].indexOf('_'))
}
let hold = new Set(arr1);
let missingPieces = new Set
hold.forEach(element => missingPieces[element] = uniformSet);



uniformPieces.forEach(e=>{
  let t = e.split('_');
  if(missingPieces.hasOwnProperty(t[0])){
    var index = missingPieces[t[0]].indexOf(t[1]);

    if (index !== -1) {
      console.log(t[0])
      missingPieces[t[0]].splice(index, 1);
     
    }

  }
  });

  console.log(missingPieces)

}

f1(uniformSet3, uniformPieces3);

When I call splice() on misingPieces, it is deleting an element in every array rather than the specific the array within the set. For example:

Set(0) {
  company1: [ 'hat', 'glasses' ],
  company2: [ 'hat', 'glasses' ]}

Then missingPieces[t[0]].splice(index, 1) is called, which should delete one element, but instead yields:

Set(0) { company1: [ 'hat' ], company2: [ 'hat' ] }

Thus deleting the element from all arrays in the set.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Non-primitive data types are passed by reference. If you would like to create a copy instead of creating another variable for the same reference, you need to clone/copy all values. If you use the second line here, my_object and another_variable_for_same_reference refer to the same object.

let my_object = {};
let another_variable_for_same_reference = my_object;
let object_with_copied_values = {...my_object};
about 4 years ago · Juan Pablo Isaza Denunciar

0

I think at a quick read over, you are storing the same reference (uniformSet) and so when you splice one, it splices all (because they are all actually the same referrence)

try copying uniformSet instead of assigning it directly

  hold.forEach(element => missingPieces[element] = [...uniformSet]);

(I didn't test this)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda