Observable array that only contains unique items?

1,454 views
Skip to first unread message

Brian Vallelunga

unread,
Jan 11, 2011, 1:23:50 PM1/11/11
to knock...@googlegroups.com
Is there any straightforward method of ensuring an observable array only allows unique items are added to it. I think ideally I'd define a function that returned the property of the item in the array I want to use as a uniqueness constraint.

var myData = ko.observableArray([]);
myData.unique(function(item) {
   return item.id;
});

myData.push(new { id: 1, name: "Bob" });
myData.push(new { id: 1, name: "Sue" });

I'd want myData to ignore the second push. I'm also open to other ways of doing this.

mkidder

unread,
Jan 14, 2011, 1:44:41 PM1/14/11
to KnockoutJS
Brian,

I played around with some code examples I found via a StackOverflow
search that compares arrays. I reworked code to conditionally add to
an array. I strongly emphasis "play" as it's never been tried and
tested in a real environment. Your mileage may vary.

http://jsfiddle.net/mikekidder/7EFnK/11/

This works independent of Knockout. I got it to work on a variety of
types. Hope you find it useful. Happy coding!
Reply all
Reply to author
Forward
0 new messages