[英]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
). 我必须迭代两个数组,如果第一个数组的
iso
属性等于address.country
验证第二个数组条件的国家,则将第二个数组的地址和slug
段( this.concessions
)分配给第一个数组( 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
数组,其中包含address
和slug
属性(除了他已经拥有的属性之外)
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 ? 我该如何优化它,在这种情况下,例如
for ..of
最好使用什么可迭代的方法?
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)
: 因此,现在查找优惠是
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. 当我们一次迭代国家而一次让步时,时间复杂度为
O(n + m)
,其中n
和m
是数组的长度。 This performance gain however is achieved with a high memory usage. 但是,这种性能提升是通过较高的内存使用量来实现的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.