I’m trying to make a drinks web application where the user enters ingredients and then return the name of the drink or cocktail.
My drinks array looks like this:
// Drinks
var drinks = new Array(
[0,['Whisky on the Rocks'],['whisky','ice']],
[1,['Vodka on the Rocks'],['vodka','ice']]
);
I have this so fare, but it is only returning the first element:
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;
}
}
}
What am I doing wrong? And is there a better way to do it?
Thanks in advance,
Robert
Ok, I would do something like this: in your
forloop, keep track of the minimum distance you’ve found and of its index:See this fiddle for a full example. By the way, I strongly recommend using a more meaningful structure for the
drinksanddifferencearrays, as suggested by VisioN, and maybe also making the function return some kind of data structure (closest drink index and ingredients array, for example) instead of a description string.