Home > Software engineering >  String being pushed into an array twice
String being pushed into an array twice

Time:01-19

I have two sets of two lists. Strings will move between each set.

In one set I will hold a list of strings that will be searched on. The other list will hold the same list of strings but the search filter will never be applied on this one.

The other set does the same thing but with different strings. Strings will be moved between the two sets but both sets will never contain the same string at the same time.

"deselectedListToBeMoved" will contain strings I need moved from one set to the other

  selectCustomer() {
  for (let deselect of this.deselectedListToBeMoved) {
    this.deselectedList = this.deselectedList.filter(
      (customer) => customer !== deselect
    );
    this.originalDeselect = this.originalDeselect.filter(
      (customer) => customer !== deselect
    );
    this.selectedList.push(deselect);
    this.originalSelect.push(deselect);
  }
  this.selectedList.sort((a, b) => a.localeCompare(b));
  this.deselectedListToBeMoved = [];
}

*HTML*
 <div id="customer_{{cus}}"  *ngFor="let cus of selectedList">{{cus}}</div>

The issue is when this is called, a string is pushed into 'selectedList' twice sometimes. And is displayed on the FE twice.

If I remove "this.originalSelect.push(deselect);" it is only pushed into 'selectedList' once.

CodePudding user response:

The most probable reason is that somewhere you have:

this.originalSelect = this.selectedList;

// or similar:
const array = [/* maybe some initial content */];
this.selectedList = array;
this.originalSelect = array;

I.e. your 2 members this.selectedList and this.originalSelect actually reference the exact same object (array).

And when mutating that object (here with its .push() method), the change is visible from both members (because they actually access the same object).


If you want to have them initially identical, but to manage them separately (here maintaining their content in sync, except for the order), you could make a shallow copy, e.g. with spread operator:

this.originalSelect = [...this.selectedList];
  • Related