【问题标题】:Search function (JAVASCRIPT)搜索功能(JAVASCRIPT)
【发布时间】:2021-01-08 03:27:10
【问题描述】:

我有一个字符串数组和一个字符串作为输入。我需要做的是获得与输入中的字母顺序相同的字符串的输出。

input-->output
(d -->[dune,to kill a mockingbird,the sun and her flowers,lord of the flies])
(du -->[dune])
(dune -->[dune])
(t -->[the sun and her flowers,the grapes of wrath,lord of the flies, to kill a mockingbird])
(the -->[the sun and her flowers,the grapes of wrath,lord of the flies])

这是我尝试做的(我知道它很复杂啊):-

var input = "du";
var sl = ["dune","to kill a mockingbird","leaves of grass","the sun and her flowers","lord of the flies","the grapes of wrath"];
var slc = [];

if(input.length<=0)
{
  slc.push("No Results Found");
}


for(var i=0; i<input.length; i++)
{
  for(var j=0; j<sl.length;j++)
  {
    for(var z=0; z<sl[j].length; z++)
    {
      if(input.charAt(i)==sl[j].charAt(z))
      {
         slc.push(sl[j]);
      }
    }
  } 
}
 
function removeDups(slc) {
  let unique = {};
  slc.forEach(function(x) {
    if(!unique[x]) {
      unique[x] = true;
    }
  });
  return Object.keys(unique);
}
slx = removeDups(slc);

【问题讨论】:

  • 你在问什么?

标签: javascript java filter


【解决方案1】:

'some string'.includes('substring') 方法将使字符串搜索更容易。另请参阅仅保留唯一值的简单方法。

var input = 'du';
var sl = ["dune", "to kill a mockingbird", "leaves of grass", "the sun and her flowers", "lord of the flies", "the grapes of wrath"];

var slc = sl.filter(str => str.includes(input));

// to make unique
slc = slc.filter((str,i)=>i===slc.indexOf(str));

【讨论】:

    【解决方案2】:

    如果您关心按出现次数排序,这会有所帮助。否则 rwusana 有一个很好的答案

    count = e => (e.match(new RegExp(input, 'g')) || []).length
    sl.filter(e => e.includes(input))
      .sort((a, b) => count(b) - count(a))
    

    【讨论】:

      猜你喜欢
      • 2015-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多