繁体   English   中英

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

[英]Find the string that all array elements begin with in 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是此数组的匹配字符串?

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

 let names = ["samantha", "sammy"]; var found = true; var r = names[0].split('').reduce(function(r, e, i) { var check = names.every(elem => elem[i] == e); check && found ? r += e : found = false; return r; }, '') console.log(r) 

 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) 

不一定高效,但类似:

 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)); 

暂无
暂无

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

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