Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an item exists in an observableArray

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>

like image 329
Jonathan Kittell Avatar asked Apr 11 '15 21:04

Jonathan Kittell


1 Answers

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.

like image 100
KSFT Avatar answered Sep 27 '22 22:09

KSFT