简体   繁体   中英

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM