R
R
Roman Chasovitin2018-09-04 11:53:53
JavaScript
Roman Chasovitin, 2018-09-04 11:53:53

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);
        }
      });
    });

But I think that this code can be improved. Can someone tell me how to write it in a more obvious way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-09-04
@RomanChasovitin

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 question

Ask a Question

731 491 924 answers to any question