How to find an element in an observable array in KnockoutJS

How to find an element in an observable array in KnockoutJS is not that hard of a task.  This is assuming that the two items you are comparing are a reference to the same item.  This is more of a custom comparison function to compare a value in an array to some other value.  To complete this we will use the ko.utils.arrayFirst from KnockoutJs.

Take a look at the following Javascript:

var match = ko.utils.arrayFirst(myObservableArray(), function(item) {
    return someValue.name === item.name;
});

Essentially what is happening here is that knockout is combing through the myObservableArray and looking for a match on name. If it finds a match then it returns that object as match. (Just wait, it’ll make sense). If it doesn’t find anything, then match is returned as undefined.

Here is the second part that deals with the match logic:

if (!match) {
  myObservableArray.push(someValue);
}

If match has a value to it and you apply the ! operator the outcome is false.

If match is undefined and you apply the ! operator the outcome is true.

So overall all, if our someValue does not exist in our myObservableArray, then we add it.


StackOverflow Profile