Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

175
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda