1

I am making a bookmark function that looks as follows:

  $scope.bookmarkPost = function(bookmark_post){
    if(window.localStorage.bookmarks == null) {
      user_bookmarks = [];
    } else {
      user_bookmarks = JSON.parse(window.localStorage.bookmarks)
    }

    var existing_post = find(user_bookmarks, function(post){ return post.title == bookmark_post.title; });

    if(!existing_post){
      user_bookmarks.push({
        id: bookmark_post.pagid,
        title : bookmark_post.title,
        date: bookmark_post.created,
        room: bookmark_post.room
      });
    }

    console.log(JSON.stringify(user_bookmarks));

    window.localStorage.bookmarks = JSON.stringify(user_bookmarks);
  };

This should work and indeed adds the post to a my array of objects if it allready exists, and then puts it in localstorage. As you can see I'm trying to check if there's allready an entry with the same title like this:

var existing_post = find(user_bookmarks, function(post){ return post.title == bookmark_post.title; });

To be 100% honest I'm not even 100% sure what this does, but I couldn't find anything else on my particular subject. This check doesn't work and thus there are duplicate entries. Does anyone know how it can be fixed?

2
  • How are you calling this function (as in, what argument are you passing in?) Where does it get this from? Commented Oct 18, 2016 at 15:16
  • 1
    What about user_bookmarks.find(function(post){ return post.title == bookmark_post.title; }); Commented Oct 18, 2016 at 15:27

1 Answer 1

2

You probably meant to use the Array.find() method:

var existing_post = user_bookmarks.find(function(post){ 
  return post.title === bookmark_post.title; //use === for strict comparison
}); //will return only first element that matches the callback criteria

Quick note: Array.find() is not supported by IE

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

1 Comment

I was wondering if find is potentially an angular function in this case though... But yeah, this is the way to do it. Also, who cares about IE? :)

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.