Hi Is KnockoutJs support filter Array for a duplicate item ?

734 views
Skip to first unread message

lovedota

unread,
Sep 13, 2011, 4:49:43 AM9/13/11
to KnockoutJS
Hi I tried this way, and it work fine. But I want to learn new way to
do it with knockout, Is knockout support filter a duplicate item ?

var opt = [
{ name: "Product 5", price: 10 },
{ name: "Product 6", price: 10 },
{ name: "Product 7", price: 20 },
{ name: "Product 8", price: 30 },
{ name: "Product 9", price: 40 }
];

var i = 0, x, count, item;

while (i < opt.length) {
count = 1, item = opt[i], x = i + 1;
while (x < opt.length && (x = opt.indexOf(item, x.price)) !=
-1) {
count += 1;
opt.splice(x, 1);
}
opt[i] = new Array(opt[i], count);
++i;
}

console.log(opt);

Thanks you !

rpn

unread,
Sep 13, 2011, 9:53:43 AM9/13/11
to knock...@googlegroups.com
I don't think that it is way better, but here is another way to do your filter.  This would only take one pass through the data and throw out any duplicates along the way.

var priceIndex {};
var filtered ko.utils.arrayFilter(optfunction(item{
    if (typeof priceIndex[item.price=== "undefined"{
       priceIndex[item.price1;
       return true
    }
    return false;
});

lovedota

unread,
Sep 13, 2011, 10:38:35 AM9/13/11
to KnockoutJS
hi your way seem to be faster, but can you please explain me more
about this, i don't understand ! Thanks !

Gopal Patel

unread,
Sep 13, 2011, 12:49:58 PM9/13/11
to knock...@googlegroups.com
he is creating another index for counting the reference, if it exist , remove it. nice idea.

if opt is observable, you could also use 

opt.remove(function(item){and do something with item,return true or false})

...what I would like to know is , how did you syntax highlight your code in email ? copy paste ?

rpn

unread,
Sep 13, 2011, 4:38:55 PM9/13/11
to knock...@googlegroups.com

...what I would like to know is , how did you syntax highlight your code in email ? copy paste ?


I hate posting code without testing it out, so I usually try it out in jsFiddle.  Copy and paste from jsFiddle preserves the highlighting.  I usually respond on the groups site rather than by replying to email.
 
Reply all
Reply to author
Forward
0 new messages