从另一个 obseravableArray 获取唯一值的 observableArray

Get observableArray of unique values from another obseravableArray

我有这样的数据:

    { mealName: "sandwich", price: 0 },
    { mealName: "lobster", price: 34.95 },
    { mealName: "whole zebra", price: 290 },
    { mealName: "whole zebra", price: 290 },
    { mealName: "sandwich", price: 290 },
    { mealName: "whole zebra", price: 290 }

我想像这样获得 observableArray:

{ mealName: "sandwich"},
{ mealName: "whole zebra"},
{ mealName: "lobster"}

我试图在 jsFiddle 中重现它,但有些地方不对

unique 不必是可观察数组,因为 availableMeals 不是可观察数组,但既然你问我使用了计算数组。

首先,我使用自定义排序函数对数组进行排序。我使用 concat 创建了一个副本,因为我不想修改原始数组的顺序。然后我遍历排序的数组并删除所有重复项:

self.unique = ko.computed(function() {
     var sortedItems = self.availableMeals.concat().sort(function(left, right) { return left.mealName == right.mealName ? 0 : (left.mealName < right.mealName ? -1 : 1) });

     var meal;

     for (var i = 0; i < sortedItems.length; i++) {                 
         if (!meal || meal != sortedItems[i].mealName) {
             meal = sortedItems[i].mealName;
         }
         else {
             sortedItems.splice(i, 1);
             i--;
         }
     }

     return sortedItems;
});     

jsfiddle

var uniqueMeals = ko.computed(function () {
    var uniqueMealNames = mealData().reduce(function(uniqueMeals, meal) {
        if(uniqueMeals.indexOf(meal.mealName) === -1) {
            uniqueMeals.push(meal.mealName);
        }
        return uniqueMeals;
    }, []);

    return uniqueMealNames.map(function(mealName) {
        return {mealName: mealName};
    });
});

一些建议:最好将唯一值存储在字符串数组中,而不是对象中,即 ["sandwich", "whole zebra", "lobster"]。如果是这样,您可以删除我上面代码中的最后一行。

此外,您可以考虑查看 lodash 库。对于 lodash,这将是:

var uniqueMeals = ko.computed(function () {
    return _.unique(_.pluck(mealData, "mealName"));
})