Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

81
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda