Brian D
Brian D

Reputation: 10153

Preventing duplicate items in a knockout.js observable array

I run a timed loop which fetches data asynchronously from the server and updates an observable array. I thought that this would prevent dups but it doesn't seem to. How can I prevent adding duplicates?

// Operations
self.addDevice = function (device) {
    if (device != null && ko.utils.arrayIndexOf(self.devices, device) < 0) {
        self.devices.push(device);
    } 
}

This is always returning true, as in the array does not contain the particular device (though it clearly does).

Upvotes: 1

Views: 3927

Answers (1)

Riley Lark
Riley Lark

Reputation: 20890

The updates you get may have all the same values as objects you have in your array, but they're probably different objects, so a simple equality check will return false. You'll have to supply a callback to test for equality yourself by comparing properties within the objects.

For example, if a = {prop: 5} and b = {prop: 5}, then a == b returns false. You need to pass in a function to ko.utils.arrayFirst or ko.utils.arrayFilter like

var newItem = new Item();

ko.utils.arrayFirst(self.items(), function(existingItem, newItem) {
    return existingItem.prop == newItem.prop;
}

Upvotes: 3

Related Questions