Reputation: 6512
I want to pass in an array of ids and filter an observable array for the items that have those ids what is the best solution?
right now im iterating through the array one by one and filtering an observable array for each individual id.
visibleCheckBoxes.each(function (i, v) {
var item = ko.utils.arrayFilter(self.batches(), function (batch) {
return batch.BatchID() == v.id;
});
});
Upvotes: 0
Views: 1116
Reputation: 3922
The following will create filtered
which contains elements from batches
whose id is in boxes
. It can be greatly simplified by using underscore or something similar.
var boxes = ko.observableArray([{id:1},{id:3}]);
var batches = ko.observableArray([{bId:1, name:"ID1"},{bId:2, name:"ID2"},{bId:3, name:"ID3"},{bId:4, name:"ID4"}]);
var filtered = ko.utils.arrayFilter(batches(), function (batch) {
for (var i = 0; i < boxes().length; i++)
if (batch.bId == boxes()[i].id)
return true;
return false;
});
Working fiddle http://jsfiddle.net/JD2Q2
So in your example it would be something like
var filtered = ko.utils.arrayFilter(self.batches(), function (batch) {
for (var i = 0; i < visibleCheckBoxes().length; i++)
if (batch.bId == visibleCheckBoxes()[i].id)
return true;
return false;
});
Upvotes: 2
Reputation: 8987
If the id is unique you'd better use arrayFirst. O(n^(n/2))
var batches = self.batches();
visibleCheckBoxes.each(function (i, v) {
var item = ko.utils.arrayFirst(batches , function (batch) {
return batch.BatchID() == v.id;
});
});
And if you have a lots of item O(2n).
batchesDict = {};
var batchesDict = ko.utils.arrayForEach(self.batches(),function(batch){
batchesDict[batch.BatchID()] = batch;
});
visibleCheckBoxes.each(function (i, v) {
var item = batchesDict[v.id];
});
I hope it helps.
Upvotes: 2