Mac L. Lak
Mac L. Lak

Reputation: 121

Javascript loop in Array method

When I have objects in Array like

    var bookIndex =  [{
      id: '1',
      title: 'First title',
      description: 'This is my first title'
    }, {
      id: '2',
      title: 'Second title',
      description: 'This is my second title'
    }];

then loop through array using for()

    function getBook(bookId){
      for (var i = 0; i < bookIndex.length; i++) {
        if (bookIndex[i].id === bookId) {
          return bookIndex[i];
        }
       }
       return undefined;
     };

I wonder how to use other loop method, to get same result. Ex. forEach. I try to use something like this but it couldn't get return object I want.

    function getBook(bookId) {
      bookIndex.forEach(function () {
        if (bookId === bookIndex.id) {
          return bookId;
        }
        return undefined;
      });
    };

Upvotes: 3

Views: 247

Answers (4)

Pointy
Pointy

Reputation: 413712

You'd use .find():

function getBook(bookId) {
  return bookIndex.find(function(book) { return book.id === bookId; });
}

The callback to .find() should return true when the criteria are satisfied. When that happens, .find() returns that element of the array. If no elements match, it returns undefined.

The .forEach() function is useful, but it really is for situations when you actually do want to perform some operation on each element of the array.

Upvotes: 6

Все Едно
Все Едно

Reputation: 726

i tought you where wondering how could you for loop and then return, and since every one witch answered you didn't used for each i desided to show you a foreach solution, hoping that this is what you had expected

var bookIndex = [
    {
        id: '1',
        title: 'First title',
        description: 'This is my first title'
    }, {
        id: '2',
        title: 'Second title',
        description: 'This is my second title'
    }];
function getBook(bookId) {
    bookIndex.forEach( function (el) {
        if (el.id === bookId) {
          getBook1(el);
        }
    });
}
getBook('2');
function getBook1(el) {
 var element = el;
    console.log(element);
}

In the bookIndex.forEach( function (el)you need to pass an argument to the function (the callback), witch you use for the forEach method. And this was your main mistake. This elment that i have passed called el is basically every element in your array witch isn't undefined or null. And since you can't just return something from the foreach, cause it returns in to the callback, not to the parrent function, in your case function getBook(index), i had to call another functuion in witch i can store the variable

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386560

You could use Array#some()

The some() method tests whether some element in the array passes the test implemented by the provided function.

function getBook(bookId) {  // returns true or false if the book exists
    return bookIndex.some(function (book) {
        return bookId === book.id;
    });
};

For returning the book object, then you might use

function getBook(bookId) {  // returns the book with the index
    var book;
    bookIndex.some(function (b) {
        if (bookId === b.id) {
           book = b;
           return true;
        }
    });
    return book;
};

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122037

You can use filter and return object with that id.

var bookIndex = [{
   id: '1',
   title: 'First title',
   description: 'This is my first title'
 }, {
   id: '2',
   title: 'Second title',
   description: 'This is my second title'
 }];

 function getBook(bookId) {
    return bookIndex.filter((e) => { return parseInt(e.id) == parseInt(bookId)})[0];
 };
 
 console.log(getBook(2))

Upvotes: 1

Related Questions