Does KnockoutJS have a feature whereas I could take something like:
var myArray = ko.observableArray([
{ name: "Jimmy", type: "Friend" },
{ name: "George", type: "Friend" },
{ name: "Zippy", type: "Enemy" }
]);
Then select distinct on the "type" field, producing a result which looks like this:
(pseudo code)
var distinct = myArray.distinct('type')
// Returns array of two arrays
// distinct[0] is an array of type=Friend
// distinct[1] is an array of type=Enemy
I'm aware of ko.utils.arrayGetDistinctValues, but that doesn't exactly do what I want. I'm also aware that I could write a few loops using ko.utils.arrayGetDistinctValues to get what I want, I'm just wondering if there is something else baked into KnockoutJS that I'm overlooking.
I have simplified RP Niemeyer's version in jsfiddle to do the same without using the distinct function. Please refer here: jsfiddle
Thanks Niemeyer.
There is not anything else built into KO to make this any easier.
There are many ways that you could make this work. For example, you could extend observableArrays to have a
distinct
function. Then, you can just create your observableArray like:The
distinct
function might look like:It supports chaining so you could call
distinct
multiple times with different properties.Sample here: http://jsfiddle.net/rniemeyer/mXVtN/
This does rebuild the index once on each change, so if you have a huge list of items, then you would want to potentially explore other ways (manual subscriptions) for adding/removing items from the "index" arrays.
Just want to add to this that if you call this
.distinct()
method twice (like maybe from a computed observable), you'll get the indexes and associated computed function called twice - rinse and repeat and you've got a performance problem on your hands.To sort this out, add this line near the top of the function: