Why is the check for duplicate Artist always returning false?
See this JSFiddle for a runnable demo.
Knockout Code
$(function() {
  function Artist(name) {
    this.name = name;
  }
  function ViewModel() {
    var self = this;
    self.favoriteArtists = ko.observableArray([]);
    self.artistToAdd = ko.observableArray("");
    self.addArtist = function () {
      var newFavoriteArtist = new Artist(self.artistToAdd());
      console.log("New Favorite Artist: " + newFavoriteArtist.name);
      var artistExists = self.favoriteArtists.indexOf(newFavoriteArtist) > 0;
      console.log("Artist Exists: " + artistExists);
      if(!artistExists) {
          self.favoriteArtists.push(newFavoriteArtist);
          console.log("A new artist has been added:" + self.artistToAdd());
      } else {
        console.log("Artist already in favorites.");
      }
    };
  }  
  ko.applyBindings(new ViewModel());
});
HTML
<h1>Favorite Artists</h1>
<p>Currently, your favorite artists include:</p>
<ul data-bind="foreach: favoriteArtists">
    <li> <span data-bind="text: name"></span>
    </li>
</ul>
<p>Enter the name of a new artist:</p>
<input data-bind="value: artistToAdd" />
<button data-bind="click: addArtist">Add</button>
                Your check should be one of these:
self.favoriteArtists.indexOf(newFavoriteArtist) >= 0
self.favoriteArtists.indexOf(newFavoriteArtist) != -1
self.favoriteArtists.indexOf(newFavoriteArtist) > -1
You're checking whether it's greater than zero. That means that if it's in position 0, artistExists will be set to false because zero is not greater than zero.
That still doesn't work, though. The array is filled with Artist objects, which can't be searched for normally, because the object you search for is different from the object in the array, even if they have the same name value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With