如何将数组与多个数组匹配并返回最接近的数组

时间:2013-01-17 10:03:51

标签: javascript arrays compare match

我正在尝试制作饮料网络应用程序,用户输入成分,然后返回饮料或鸡尾酒的名称。

我的饮料阵列看起来像这样:

 // Drinks
 var drinks = new Array(
    [0,['Whisky on the Rocks'],['whisky','ice']],
    [1,['Vodka on the Rocks'],['vodka','ice']]
);

我有这样的票价,但它只返回第一个元素:

function compare(myDrink) {
var difference = [];
difference[0]  = [];
difference[0][0] = [];
var dCount = drinks.length;
for (x = 0;x < dCount; x++) { 
    jQuery.grep(drinks[x][2], function(el) {
        if (jQuery.inArray(el, myDrink) == -1){
             difference[x][0].push(el);
             difference[x][1] = difference[x][0].length;
        }
    });
    var theDrink = difference[x][0].join(',');
    if (theDrink == ''){
        return drinks[x][1];
    } else {
        var diff = 'The Difference is: ' + difference[x][1] + ' Missing: ' + theDrink;
        return diff;
    }

}
}

我做错了什么?还有更好的方法吗?

提前致谢,

罗伯特

1 个答案:

答案 0 :(得分:1)

好的,我会这样做:在你的for循环中,跟踪你找到的最小距离及其索引:

....
var closest = -1;
var minDifference = 99;
for (x = 0;x < dCount; x++) {
    difference[x]  = [];
    difference[x][0] = [];
    difference[x][1] = 0;
    jQuery.grep(drinks[x][2], function(el) {
        if (jQuery.inArray(el, myDrink) == -1){
            difference[x][0].push(el);
            difference[x][1] = difference[x][0].length;
        }
    });
    if (difference[x][1] < minDifference) {
        minDifference = difference[x][1];
        closest = x;
    }
}
...

有关完整示例,请参阅this fiddle。顺便说一句,我强烈建议为VisioN建议的drinksdifference数组使用更有意义的结构,也可能使函数返回某种数据结构(最近的饮料索引和成分)例如,数组而不是描述字符串。