Home > database >  Why are all of the arrays deleting an element in this set instead of the one being referenced?
Why are all of the arrays deleting an element in this set instead of the one being referenced?

Time:04-27

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.

CodePudding user response:

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)

CodePudding user response:

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};
  • Related