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

179
Visualizações
Find an item using reduce() in JavaScript

I have an array of objects. I want to loop trough that array and to check if an item match a criteria, using reduce method from javascript:

const arr = [{
    value: 'test',
    label: 'Test'
  },
  {
    value: 'car',
    label: 'Car'
  },
]


const res = arr.reduce((acc, item) => {
  if (item.value) {
    acc.push({
    element: item.label,
    id: item.value,
    })
  }
  if(item.value !== 'car') {
    acc.push({element: 'here', id: 'here'})
  }
  return acc
}, [])

console.log(res)

Using if(item.value !== 'car') { acc.push({element: 'here', id: 'here'}) } i try to inspect if in my list is not at all a value that is not equal with 'car', then add that object, but it adds even if in the list exists car title, but what i want to achieve is to see if in the array is not any item that is equal with car, only after that to add that object. How to achieve that without using find() but only reduce()?
Examples: 1. if i check the title car then that object should not be added . 2. If i check the title 'unknown', then that object should be added.

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

0

As I understood you only need to filter by some elements (not car elements). This way, you don't need to use "reducer", you can use "filter". Please, check the code below:

const arr = [{
    value: 'test',
    label: 'Test'
  },
  {
    value: 'car',
    label: 'Car'
  },
];

// Using filter (recommended in your case)
// const notCarElements = arr.filter(elem => elem.value !== 'car');

// Using reducer
const notCarElements = arr.reduce((acc, item) => {
  if (item.value === 'car') return acc;
  acc.push(item);
  return acc;
}, []);

console.log(notCarElements);

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