Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda