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

136
Visualizações
Javascript modify object in filter array

I have an array of objects that I need to filter. I am wondering if it is possible to modify the object in the filter function. I dont want to use .map then .filter because then it would loop thru the array twice making it take more time and wont scale if there are thousands of items in the list.

const cities = [
  {name: 'Los Angeles', population: 100},
  {name: 'New York', population: 80},
  {name: 'Chicago', population: 120},
  {name: 'Houston', population: 60},
  {name: 'Philadelphia', population: 70}
];

const highPopulation = cities.filter(item => {
  // item.isHighPopulation = true
  return item.population >= 100
});

console.log(highPopulation)

Maybe filter isnt the best solution to this problem. I just dont want multiple unessecary loops if I can do this operation in one loop.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Using Array#reduce:

const cities = [
  {name: 'Los Angeles', population: 100},
  {name: 'New York', population: 80},
  {name: 'Chicago', population: 120},
  {name: 'Houston', population: 60},
  {name: 'Philadelphia', population: 70}
];

const highPopulation = cities.reduce((items, item) => {
  if(item.population >= 100) items.push({...item, isHighPopulation: true});
  return items;
}, []);

console.log(highPopulation)

Using Array#filter and Array#map:

const cities = [
  {name: 'Los Angeles', population: 100},
  {name: 'New York', population: 80},
  {name: 'Chicago', population: 120},
  {name: 'Houston', population: 60},
  {name: 'Philadelphia', population: 70}
];

const highPopulation = cities
  .filter(({ population }) => population >= 100)
  .map(item => ({...item, isHighPopulation: true}));

console.log(highPopulation)

about 4 years ago · Juan Pablo Isaza Relatório

0

With forEach loop, in one iteration and add items to results only on filter criteria

const cities = [
  { name: "Los Angeles", population: 100 },
  { name: "New York", population: 80 },
  { name: "Chicago", population: 120 },
  { name: "Houston", population: 60 },
  { name: "Philadelphia", population: 70 },
];

const isHigh = ({ population }) => population >= 100;

const highPopulation = (arr, res = []) => {
  arr.forEach(
    (item) => isHigh(item) && res.push({ ...item, isHighPopulation: true })
  );
  return res;
};

console.log(highPopulation(cities));

about 4 years ago · Juan Pablo Isaza Relatório

0

I am wondering if it is possible to modify the object in the filter function.

It is possible. The code you've posted would do what you're asking if you uncomment the commented line.

It is also a bad idea. Mutating objects in a transformation method like filter violates the command-query separation principle.

I dont want to use .map then .filter

Hopefully you're not modifying objects in map either: you should be creating new objects instead. Something like .map(item => {...item, isHighPopulation: item.population >= 100}).

because then it would loop thru the array twice making it take more time and wont scale if there are thousands of items in the list.

Have you tested this assumption? In my experience it's rare for something to take an acceptable amount of time to do x operations, but an unacceptable amount of time to do 2x operations. If performance is an issue for you, it's probably better to take a broader look at your algorithms and data models. If not, you should probably not be worrying overmuch about it.

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