简体   繁体   English

Javascript通过匹配字符串对数组进行排序

[英]Javascript sort an array by matching to string

I have an array containing results form a geolocation code. 我有一个包含结果的数组,这些结果来自地理位置代码。 I want to sort it by the closest match to the term that I have searched. 我想按与搜索到的词最接近的方式对它进行排序。

Example. 例。 Search: Pizza . 搜索: Pizza

Array: Pizza Uno, Pizzeria Uno, Burgers and Pizzeria, Cino Pizzeria. 

The sorted array should be: 排序后的数组应为:

Pizza Uno,
Pizzeria Uno,
Burgers and Pizzeria,
Cino Pizzeria. 

Thanks for your help. 谢谢你的帮助。

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. 当然有更好的解决方案,例如,您可以看一下sift算法,它实际上比levenshtein的方法快得多。

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'];

A really basic algorithm that'd work, would be to sort based on what percentage of the total string length, the match takes up. 一个真正有效的基本算法是根据匹配占字符串总长度的百分比进行排序。 So an exact match of "Pizza" would be 5/5 (100%), the "Pizza Uno" match would be 5/9, "Pizzeria Uno" is 4/12, and so on. 因此,“ Pizza”的精确匹配为5/5(100%),“ Pizza Uno”的匹配为5/9,“ Pizzeria Uno”为4/12,依此类推。 This is one of the core components of the MySQL natural sorting algorithm at its most basic. 从本质上讲,这是MySQL自然排序算法的核心组件之一。

You can try calculating the Levenshtein Distance between 2 strings. 您可以尝试计算2个字符串之间的Levenshtein距离 It's basically the number of steps it will take to make the two strings identical. 基本上,这是使两个字符串相同所要执行的步骤数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM