查找唯一的前缀并从字符串数组中删除

时间:2018-05-04 11:02:43

标签: javascript arrays

在Javascript中,给定一个字符串数组,如何找到所有字符串的唯一前缀,然后从每个字符串中删除该前缀。

例如:

["05098701", "05012302", "0545621", "0509301"]

唯一前缀是" 05"

结果数组将是

["098701", "012302", "45621", "09301"]

1 个答案:

答案 0 :(得分:3)

你需要像人类一样进行搜索:检查一个字符,然后选择两个,依此类推......

然后只是来自数组中每个项目的remove 前缀。 您可以使用map方法通过传递回调函数来执行此操作。



array = ["05098701", "05012302", "0545621", "0509301"]
function longestCommonPrefix(arr){
    // sort() method arranges array elements alphabetically
    var sortArr = arr.sort();
    
    // Get first array element    
    var arrFirstElem = arr[0];
  
    // Get the last array element length minus one
    var arrLastElem = sortArr[sortArr.length - 1]; 
    
    // Get first array element length
    var arrFirstElemLength = arrFirstElem.length; 
    
    // Set "i" incrementer to 0
    var i= 0;
    
    // while "i" is less than the length of the first array element AND
    // the first array element character position matches the last array character position
    // increment "i" by one
    while(i < arrFirstElemLength && arrFirstElem.charAt(i) === arrLastElem.charAt(i)) {
      i++;
    }
    
    //return the prefix
    return arrFirstElem.substring(0, i);
}
 

prefix = longestCommonPrefix(array);
array = array.map(function(item){
    return item.substring(prefix.length, item.length);
});
console.log(array);
&#13;
&#13;
&#13;

相关问题