Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

80
Views
How to optimize big array comparision

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);
  }
};
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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

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

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!