What about something like this? It was my first approach for getting the closest color name, depending on a hex-color.
There's of course a better solution out there, you could for example take a look at the sift
algorithm which is really much faster than levenshtein's approach.
However this should work for you as expected.
Array.closest = (function () {
function levenshtein(s, t) {
if (!s.length) return t.length;
if (!t.length) return s.length;
return Math.min(
levenshtein((s.substring(1), t) + 1,
levenshtein((t.substring(1), s) + 1,
levenshtein((s.substring(1), t.substring(1)) + (s[0] !== t[0] ? 1 : 0)
);
}
return function (arr, str) {
return arr.sort(function (a, b) {
return levenshtein((a, str) - levenshtein((b, str);
});
};
}());
var arr = ['Pizza Uno', 'Pizzeria Uno', 'Burgers and Pizzeria', 'Cino Pizzeria.'];
Array.closest(arr, 'Pizza') // => ['Pizza Uno', 'Pizzeria Uno', 'Cino Pizzeria.', 'Burgers and Pizzeria'];