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

174
Views
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 answers
Answer question

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 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!