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.


2 thoughts on “How to find an element in an observable array in KnockoutJS

  1. Srikanth

    Thanks a lot .. This works like a charm and I wonder this is not in the official Knockout portal as well.

    Thanks again, it was such a saving grace.

    Regards,
    Srikanth

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

StackOverflow Profile