I would like to push
a new item onto an observableArray
, but only if the item is not already present. Is there any "find" function or recommended pattern for achieving this in KnockoutJS?
I've noticed that the remove
function on an observableArray
can receive a function for passing in a condition. I almost want the same functionality, but to only push it if the condition passed in is or is not true.
An observableArray exposes an indexOf
function (wrapper to ko.utils.arrayIndexOf
). This allows you to do:
if (myObservableArray.indexOf(itemToAdd) < 0) { myObservableArray.push(itemToAdd); }
If the two are not actually a reference to the same object and you want to run custom comparison logic, then you can use ko.utils.arrayFirst
like:
var match = ko.utils.arrayFirst(myObservableArray(), function(item) { return itemToAdd.id === item.id; }); if (!match) { myObservableArray.push(itemToAdd); }
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