在Javascript中查找所有数组元素开头的字符串

时间:2017-11-19 22:56:41

标签: javascript

我有一个字符串["samantha", "mike", "john", "sammy", "carla"]数组,输入值为s

const input = "s";
let names = ["samantha", "mike", "john", "sammy", "carla"];
let filteredNames = names.filter(name => name.startsWith(input));

这给了我“samantha”和“sammy”的结果。

如何提取filteredNames的所有元素开头的字符串?所以基本上:我怎样才能发现sam是这个数组的匹配字符串?

3 个答案:

答案 0 :(得分:4)

您可以在结果数组的第一个元素上使用stdin=True,然后使用reduce()检查每个具有相同索引的元素中的当前字母是否相同。



every()




答案 1 :(得分:0)

const input = "s"
let names = ["samantha", "mike", "john", "sammy", "carla"]
let fN = names.filter(name => name.startsWith(input))
let result = ""
if(fN.length){
    result = input
    for(let i=1; fN.every(x=>x[i]==fN[0][i]); i++)
        result += fN[0][i]
}
console.log(result)

答案 2 :(得分:0)

不一定高效,但有点像:

function findCommonPrefix(array) {
   let prefix = "";
   const smallest = findSmallestString(array);

   while (prefix.length < smallest) {
      let test = prefix + array[0][prefix.length];
      if (!(array.every(item => item.indexOf(test) == 0)))
         return prefix;
      prefix = test;
   }
   return prefix;
}

function findSmallestString(array) {
   if (array.length <= 0)
      return -1;

   let smallest = Number.MAX_SAFE_INTEGER;
   for (let x = 0; x < array.length; x++) {
      const len = array[x].length;
      if (smallest > len)
         smallest = len;
   }
   return smallest;
}

let stuff = ["sammy", "samuel"];
console.info(findCommonPrefix(stuff));

stuff = ["sammy", "samuel", "susan"];
console.info(findCommonPrefix(stuff));

stuff = ["sammy", "samuel", "susan", "joe"];
console.info(findCommonPrefix(stuff));