Answer the question
In order to leave comments, you need to log in
How to compare 2 arrays and, based on them, make a new array from the elements that are in both arrays?
Good day to all. There was such question: There are 2 arrays, an array of cities (objects) and an array of id of these cities. Id of each city is, respectively, also in the objects. Now, in order to compare these 2 arrays and write to the new one those objects whose id is in the first array, I use this construction:
this.defaultCitiesIds.forEach((def) => {
this.allCities.forEach((city) => {
if (def === city.id) {
city.check = false;
this.visibleCities.push(city);
}
});
});
Answer the question
In order to leave comments, you need to log in
this.visibleCities = this.allCities.filter(city => this.defaultCitiesIds.includes(city.id))
.map(city => ({ ...city, check: false }));
this.visibleCities = this.allCities.reduce((result, city) => {
if (this.defaultCitiesIds.includes(city.id)) {
city.check = false;
result.push(city);
}
return result;
}, []);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question