0

I'm using Angular 6.

In my component I have two array variables like

processedItems: Array<any> = [];
totalProductItems: Array<any> = [];

and processing functions like

ngOnInit() {
  $products.forEach(async (e) => {
    const res = await this.scraperService.scrapSingle(e.url).toPromise();
    if (res.status.http_code === 200) {
      const properties = this.scraperService.processSingleProduct(res.contents);

      const p_item = {};
      p_item['properties'] = properties;

      this.totalProductItems.push(p_item);

      this._applyFilter();
    }
  }


private _applyFilter() {
  if (!this.filterData) {
    // if nothing to filter, set totalProductItems;
    this.processedItems = this.totalProductItems;
  } else {
    console.log('applying filter');

    // reset processedItems
    this.processedItems.length = 0;

    // this now prints blank array
    console.log(this.totalProductItems);

  }
} 

Setting length property of this.processedItems to 0 is also emptying the this.totalProductItems.

Why so? How can I keep these variables separate and independent?

Anuj TBE
  • 9,198
  • 27
  • 136
  • 285
  • 2
    Because `this.processedItems = this.totalProductItems;`: bith variables reference the same array. – JB Nizet Sep 19 '18 at 20:38
  • 2
    Possible duplicate of [How to clone a Javascript Array of Objects?](https://stackoverflow.com/questions/42523881/how-to-clone-a-javascript-array-of-objects) – Kirk Larkin Sep 19 '18 at 20:40

1 Answers1

1

As stated here:

if you assign an array to a variable or pass an array to a function, it is the reference to the original array that is copied or passed, not the value of the array.

So, when changing length property in your local array you actually modifying also referenced array.

Some solutions: assign to your variable a copy of array, which may be achieved in several ways:

  • this.processedItems = [...this.totalProductItems];
  • this.processedItems = this.totalProductItems.concat();
  • this.processedItems = this.totalProductItems.slice(0);

or instead of modifying length property reset a whole local array:

instead of this.processedItems.length = 0;, do:

this.processedItems = [];
Andriy
  • 14,781
  • 4
  • 46
  • 50