按最大匹配

时间:2017-03-01 06:11:23

标签: javascript arrays

我想在字符串中搜索所有匹配并返回按最大匹配结果排序的所有结果,让我们说我有一些字符串:

var strArray = [
  "This is my number one string",
  "Another string that contains number",
  "Just for example string"
];

// Results of search "another number" should be:
var resultArrayOfIndexes = [1, 0];

到目前为止,我可以搜索一个字符串,但它返回所有索引,其中至少有一个匹配,但我希望结果数组按匹配的最大计数排序。 我的代码:

function findMatch(list, phrase) {
  var preparedList = [],
    value = "";
  if (config.get("list").match.enabled) {
    for (var i = 0, length = list.length; i < length; i += 1) {

      value = config.get("getValue")(list[i]);
      var words = phrase.split(' ');
      var listMatchArr = [];
      $.each(words, function(idx, word) {
        var W = word.replace(/[\W_]+/g, ""); // match on alphaNum chars only
        if (match(value, W) && $.inArray(i, listMatchArr) == -1) { //phrase
          preparedList.push(list[i]);
          listMatchArr.push(i);
        };
      });

    }

  } else {
    preparedList = list;
  }

  return preparedList;
}

2 个答案:

答案 0 :(得分:0)

我假设需要进行不区分大小写的搜索。

以下代码将短语更改为单个单词的数组,然后映射列表以获取{index: 0, matches:1}形式的对象数组,然后筛选出没有匹配的对象,然后排序,然后再次映射以获得指数。

function findMatch(list, phrase) {
  var searchTerms = phrase.toLowerCase().split(/\s+/);
  return list.map(function(v, i) {
    v = v.toLowerCase();
    return {
      index: i,
      matches: searchTerms.reduce(function(a, c) {
        return a + (v.indexOf(c) !=-1 ? 1 : 0);
      }, 0)
    };
  })
  .filter(function(v) { return v.matches > 0; })
  .sort(function(a, b) { return b.matches - a.matches; })
  .map(function(v) { return v.index; });
}

var strArray = [
"This is my number one string", "Another string that contains number","Just for example string"
];

console.log(findMatch(strArray, "another number"));

或者扩展以下内容与ES6功能基本相同:

function findMatch(list, phrase) {
  var searchTerms = phrase.toLowerCase().split(/\s+/);
  return list.map(function(v, i) {
    v = v.toLowerCase();
    return {
      index: i,
      matches: searchTerms.reduce((a, c) => a + (v.includes(c) ? 1 : 0), 0)
    };
  })
  .filter(v => v.matches > 0)
  .sort((a, b) => b.matches - a.matches)
  .map(v => v.index);
}

var strArray = [
"This is my number one string", "Another string that contains number","Just for example string"
];

console.log(findMatch(strArray, "another number"));

答案 1 :(得分:0)

如果您熟悉正则表达式,则可以使用正则表达式匹配您的短语,并计算字符串中匹配的单词数。 假设您想知道匹配了多少单词,您可以将其存储为对象数组,其中每个对象存储计数和目标字符串。

var strArray = [
    "This is my number one string", "Another string that contains number", "Just for example string"
];

function findMatch(list, phrase){
    var words = phrase.split(" ");

    var pattern = "";
    var length = words.length;
    // create pattern for regex match
    for(var i = 0; i < length; i++){
        pattern += words[i];
        if(i < length-1){
            pattern += "|";
        }
    }

    var counts = [];
    var re = new RegExp(pattern,"g");
    for(var i = 0; i < list.length; i++){
        var count = (list[i].toLowerCase().match(re) || []).length;
        //add to array if matched
        if(count > 0){
            counts.push({count:count,string:list[i]});
        }
    }
    //sort by max match 
    counts.sort(function(a,b){
        return b.count-a.count;
    });

    console.log(counts);
}

findMatch(strArray, "another number");

结果将类似于:

[ { count: 2, string: 'Another string that contains number' },
  { count: 1, string: 'This is my number one string' },
  { count: 0, string: 'Just for example string' } ]