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

150
Views
Where is the mistake in this find method?

The code works with a simple foreach function, but not with a find method. Here is the forEach code:

getItemById: function (id) {
    let found = null;
    data.items.forEach(item => {
     if (item.id === id) {
      found = item;
     }
    });
    return found;
}

Here is the code with a find mehtod:

getItemById: function (id) {
      let item = data.items.find(item => {
        item.id === id;
      });
      return item;
    }

Why doesn't work the code with the find method?

also here is the array of the objects:

const data = {
    items: [
      { id: 0, name: 'Steak Dinner', calories: 1200 },
      { id: 1, name: 'Sausage', calories: 1100 },
      { id: 2, name: 'Eggs', calories: 200 },
    ],
    currentItem: null,
    totalCalories: 0,
  }
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

The find expects a predicate function as a callback and return the value that satisfy the condition. If you won't return then undefined will return by default and undefined is considered as a falsy value.

You are not returning anything from the find function. find will not consider a match if predicate function won't return true. There is not a single match that returns true in any case because all values returned by find is undefined

return item.id === id. 

const data = {
  items: [
    { id: 0, name: "Steak Dinner", calories: 1200 },
    { id: 1, name: "Sausage", calories: 1100 },
    { id: 2, name: "Eggs", calories: 200 },
  ],
  currentItem: null,
  totalCalories: 0,
};

const obj = {
  getItemById: function (id) {
    let item = data.items.find((item) => {
      return item.id === id;
    });
    return item;
  },
};

console.log(obj.getItemById(0));

about 4 years ago · Juan Pablo Isaza Report

0

getItemById: function (id) {
      return data.items.find(item => item.id === id);
    }

You don't have to use "{" and ";" in data.items.find() method. Because,the find is a predicate function

about 4 years ago · Juan Pablo Isaza Report

0

You're not returning the boolean inside find's callback

let item = data.items.find(item => {
    return item.id === id;
});
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!