Home > other >  How to optimize big array comparision
How to optimize big array comparision

Time:05-16

I am working on one Reactjs project- where i have cities and areas of each city ,in each city it may have more the 200 areas . Each area is having 3 attributes cityId,AreaID ,isAdded,. And city is have one attribute cityId.

Here i need to store Areas of each city in a separate array.How can i optimize this operation

export const getAreas = (cityID,allAreas) => {
  try {
    let areas = [];
    if (allAreas) {
     allAreas?.forEach((area) => {
        if (area?.cityID === cityID) {
          areas.push(area);
        }
      });
      return areas;
    }
  } catch (error) {
    console.log(error);
  }
};

CodePudding user response:

const areasPerCity = new Map();
allAreas.forEach((area) => {
  if (!areasPerCity.get(area.cityId)) {
    areasPerCity.set(area.cityId, []);
  }
  areasPerCity.get(area.cityId).push(area);
});
return areasPerCity; 
// here, you have a Map of a city ID => array of areas
// you could use it like `const areas = areasPerCity.get(cityId);`

Complexity is O(n) with one iteration.

CodePudding user response:

If by optimise you mean wanted to shorten your provided snippet, the below is a shorter version of your example. The Array.prototype.filter array method works great here for filtering down your initial array.

Although this isn't much faster if you were looking to optimise for algorithm speed.

const getAreas = (cityID, allAreas) => allAreas.filter((area) => area.cityID === cityID)
  • Related