Javascript用子字符串搜索匹配两个数组

时间:2019-01-16 21:05:33

标签: javascript arrays

嗨,我非常感谢您在此方面的所有帮助。我有两个数组,第一个是不带扩展名的文件名,第二个包含扩展名。我需要匹配文件名并输出匹配的第三个数组。

ArrayFileName = [one, two, three, three, five, six, ten]
ArrayFileNameWExt = [one.txt, two.txt, three.txt, ten.wmf, eleven.cgm]

输出数组为

NewArrayFileNameWExt = [one.txt, two.txt, three.txt, ten.wmf]

感谢您的所有帮助。 马克西姆

5 个答案:

答案 0 :(得分:2)

使用第二个数组上的filter()并使用正则表达式来测试每个filename是否包含在第一个数组中即可轻松实现:

ArrayFileName = [
  "one", "two", "three", "three", "five", "six", "ten", "dot.dot"
];

ArrayFileNameWExt = [
  "one.txt",
  "two.txt",
  "three.txt",
  "ten.wmf",
  "eleven.cgm",
  "dot.dot.csv",
  "foo",
  ".",
  ""
];

let res = ArrayFileNameWExt.filter(x =>
{
    let matchs = x.match(/(.*)\.(.*)$/);
    return ArrayFileName.includes(matchs && matchs[1]);
});

console.log(res);

答案 1 :(得分:1)

那又怎么样呢?

var ArrayFileName = ["one", "two", "three", "three", "five", "six"];
var ArrayFileNameWExt = ["one.txt", "two.txt", "three.txt", "ten.wmf"];

var NewArrayFileNameWExt = ArrayFileNameWExt
    .filter(file => ArrayFileName.includes(file.split(".").slice(0, -1).join(".")));
        
console.log(NewArrayFileNameWExt);

或者以更具可读性的方式:

var NewArrayFileNameWExt = ArrayFileNameWExt.filter(function(file) {
    var filename = file.split(".").slice(0, -1).join(".");
    return ArrayFileName.includes(filename);
});

答案 2 :(得分:1)

您需要遍历两个数组并进行字符串比较。 您也可以执行ArrayFileNameWExt [extName] .indexOf(ArrayFileName [fName])!= -1

for(fName in ArrayFileName){
 for(extName in ArrayFileNameWExt){
  if(ArrayFileNameWExt[extName].split('.')[0] == ArrayFileName[fName]){
   NewArrayFileNameWExt.push(ArrayFileNameWExt[extName];
  }
 }
}

应该这样做。

如果文件名带有“。”在其中执行element.indexOf(string)!= -1

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

答案 3 :(得分:1)

使用数组过滤器方法:

NewArrayFileNameWExt = ArrayFileNameWExt.filter(filename => {
    ArrayFileName.indexOf(filename.split('.').slice(0, -1).join('.')) != -1
};

这也说明文件my.filename.txt

答案 4 :(得分:1)

这是您可以轻松完成此操作的方式

var ArrayFileName = ['one', 'two', 'three', 'three', 'five', 'six', 'ten'];
var ArrayFileNameWExt = ['one.txt', 'two.txt', 'three.txt', 'ten.wmf', 'eleven.cgm'];
var FinalArray = [];

for (var i = 0; i < ArrayFileName.length; i++) {
    for (var j = 0; j < ArrayFileNameWExt.length; j++) {
        var temp = ArrayFileNameWExt[j].split(".");
        if(ArrayFileName[i]==temp[0]){
            FinalArray.push(ArrayFileNameWExt[j]);
            break;
        }
    }
}