The best way to merge two arrays in one array and filter this

I need a suggestion to merge two arrays that get data from promise and filter this merged array.

I try but i have a trouble with async data.

public sponsored_items: any = [];

constructor() {
this.get_structures();
this.get_banners();
this.arrayFilter();
}

  get_structures() {
    this.getStrucutres.get_structures(1)
      .then(data => {
        console.log(data);
        this.partners = data.results
        this.arraypartners = this.partners

        for (var i = 0; i < this.partners.length; i++) {
          if (this.partners[i].sponsored == "1") {
            this.sponsored_items.push(this.partners[i]);
          }
        }
      });
  }


  get_banners() {
    this.getBanners.get_banners(1)
      .then(data => {
        console.log(data);
        this.banners = data.results

        for (var i = 0; i < this.banners.length; i++) {
          this.banners[i].banner = true;
          this.sponsored_items.push(this.banners[i]);
        }
      });
  }

  arrayFilter() {
    console.log(this.sponsored_items);
    this.shuffleArray(this.sponsored_items);
    this.sponsored_items = this.sponsored_items.filter((item, index) => index < 1);
    console.log(this.sponsored_items);

  }

  shuffleArray(array) {
    array.sort(function (a, b) {
      return (0.5 - Math.random());
    });
  }

The function arrayFilter is executed but I need that this.sponsored_items is filled

This is a problem with async data can I resolve with a good pattern?

Thank You!

You can use forkJoin for this.

See this link.

I have two different promises that i retrieve data.
After i retrieve data in two different arrays what is the best way to merged this arrays considering that these are async data?

Use Promise.all, similar to my answer in another thread this morning.

Yep. I usually find sites like Mozilla, etc. more confusing than helpful, but docs on promise.all are actually pretty cut and dry helpful

I would suggest a really simple adjustment - just call the next function after the first function is returned.
Note: because http is async the reference to this is not there but it is easy to get round by with a var beforehand.

It is not as elegant as Promise.all() but is easier to understand if the numbers of calls are not that many.

I have put the adjustments in bold print:

1 Like

Thank You for your solution :slight_smile:

Not sure your shuffle function is ideal - have a look at the following: