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

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

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 Denunciar

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 Denunciar

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