venndi
venndi

Reputation: 171

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

Upvotes: 0

Views: 64

Answers (5)

Nice Books
Nice Books

Reputation: 1861

If a lambda function contains a single expression, it is returned automatically. (; and {} are not part of an expression ) Otherwise the return statement is a must, to return a value.

find accepts a predicate & such it must return a boolean.

Either do,

let item = data.items.find(item => item.id === id);

Or,

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

Upvotes: 0

ismail kaşan
ismail kaşan

Reputation: 31

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

Upvotes: 1

DecPK
DecPK

Reputation: 25408

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

Upvotes: 2

overflowhidden
overflowhidden

Reputation: 46

You just forgot the return statement in your find function. So it will run through all items and result nothing currently.

So just return the result of item.id === id and you're fine.

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

Upvotes: 1

Ramesh Reddy
Ramesh Reddy

Reputation: 10662

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

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

Upvotes: 1

Related Questions