1

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 ?

2
  • 5
    Why are you using map if you don't return anything? Commented Jan 12, 2018 at 14:04
  • 1
    Well, your algorithm is O(n^2). So, it isn't going to scale well. I would suggest using a for loop over a map. You may use for ... of if you want. It should work. If you really wanted fast performance, and are willing to sacrifice some memory, you can make an object/map where the keys are the countries and the values are the object from these arrays. That would introduce a constant time lookup, an only increase memory a little because the object/map would reference the objects in the array, not create a new object. Commented Jan 12, 2018 at 14:16

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

On the bright side, for this strategy, he can keep his arrays and the Map will simply reference the objects in the arrays, not create new ones. That also means he can create different maps to allow for constant time lookup of multiple properties without doubling or tripling the amount of memory he is taking up.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.