Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

203
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!