1

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);
  }
};
Nagerna
  • 33
  • 3

4 Answers4

1
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.

Igor Loskutov
  • 2,157
  • 2
  • 20
  • 33
0

You can use useMemo hook. it can memorise your returned value.

https://www.w3schools.com/react/react_usememo.asp

BIRKAN
  • 81
  • 4
-1

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.

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

Although this isn't much faster if you were looking to optimise for algorithm speed. If you want to improve this, the answers found here "What's the fastest way to loop through an array in JavaScript?" might help you speed up the loop which will have the biggest impact on performance.

Jack
  • 220
  • 1
  • 8
-1

The fastest JavaScript iteration by FAR is the basic for loop, so something like this would be much faster:

export const getAreas = (cityID,allAreas) => {
  try {
    let areas = [];
    if (allAreas) {
     for(let area = 0; area < allAreas.length; area++){
        if (allAreas[area].cityID === cityID) {
          areas.push(allAreas[area]);
        }
      });
      return areas;
    }
  } catch (error) {
    console.log(error);
  }
};
KoderM
  • 382
  • 2
  • 15