Mouad Ennaciri
Mouad Ennaciri

Reputation: 1279

JavaScript - Optimizing a two array.map loop

I have to iterate two arrays, if the iso propery of the first array is equal to address.country of the second array condition is verified, assign address and slug of the second array (this.concessions) to the first array (this.countries).

At the end, you need to have a new this.countries array that contains the address and slug property (in addition to the properties he already had)

this.countries.map((element) => {
  this.concessions.map((value) => {
    if (element.iso === value.address.country) {
      element.address = value.address
      element.slug = value.slug
    }
  })
})

How can I optimize this, and for this case what is the best iterable to use, for ..of for example ?

Upvotes: 1

Views: 1309

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138557

Just use an address map:

 const dataByCountry = new Map();
 for(var {address, slug} of this.concessions)
    dataByCountry.set(address.country, {address, slug});

So now looking up a concession is O(1):

for(var country of this.countries){
   const {address, slug}  =  dataByCountry.get(country.iso);
   if(address && slug){
     country.address = address;
     country.slug = slug;
  }
}

As we iterate countries once and concessions once, the time complexity is O(n + m) where n and m are the lengths of the arrays. This performance gain however is achieved with a high memory usage.

Upvotes: 5

Related Questions