3

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;
      });
    };
6
  • 1
    There is no '====' operator in javascript. Change it to '==='. Commented May 11, 2016 at 14:34
  • You need to array loop or array search? Commented May 11, 2016 at 14:36
  • should getBook() return a book or an index? if just the inde, the you have already one, then you need only true or false. Commented May 11, 2016 at 14:40
  • getBook() should return book as an object. I mean 1 object from bookIndex array. Commented May 11, 2016 at 14:56
  • 1
    The real question is do you want to find the first occurrence or all occurrences..? If you want the first occurrence you best use Array.prototype.find() but if you need all occurrences then Array.prototype.filter() is your friend. Commented May 11, 2016 at 15:51

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

4 Comments

if find is implemented.
As alternative for array.find() you can use array.filter()[0].
@user2415266 yes, that works too, but .find() stops as soon as it finds a match while .filter() will always process the entire array.
@Pointy it was meant as alternative because find() isn't implemented in all browsers: developer.mozilla.org/en/docs/Web/JavaScript/Reference/…
1

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

3 Comments

Is there any reason to define anonymous functions with (e) =>{} rather than function(e){}? I've seen the first syntax alot recently on the web, while I always use the second.
If you return result though you will return an array. I would suggest to return result[0]. This way you will always return the first found element OR undefined if no element was found. Since the filter is applied by Id there shouldn't be more than 1 result anyways.
That is a great idea.
1

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

4 Comments

It looks like he wants to get the element back though, not just if it is in the array. some() only returns true or false.
Again, there is no '====' operator in javascript. If you do want to prevent type coersion use '==='.
@NinaScholz Sure it's possible that way. I still prefer the find() method, but as you stated correctly this is not supported in all browsers yet. Using filter()[0] seems the most appealing solution for me.
@user2415266, filter is iterating over all elements of the array. this is here not necessary, because a wanted element could be at the beginning of the array. for a short circuit, there are only two methods of array: some and every.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.