寻找子字串时无法传回阵列的长度

时间:2019-02-15 17:04:07

标签: javascript arrays

当满足子字符串条件时,如何返回数组的长度?我有三个数组:

arr1 = ["V1","V1","V1","V1","V1","V2","V2","V2"...]
arr2 = ["A1","A1","B1","B1","B1","A2","A2","A2"...]
arr3 = ["V1A1*","V1A1*","V1B1*","V1B1*"...]

如何返回经过过滤的arr3的长度,其中arr1 [i] + arr2 [i]是元素的子字符串? (“ V1A1”)

对于第一次迭代,此处的预期输出为2。 (i = 0)

谢谢!

3 个答案:

答案 0 :(得分:2)

您似乎在说这三个数组的长度相同,并且对于数组的每个索引const mongoose = require("mongoose"); const Schema = mongoose.Schema; const schema = new Schema({ name: String, address: String, }); ,您想知道i是否是{{1}的子字符串}。然后,您想知道有多少元素满足此条件。

要完成此操作,您将需要查看数组的索引并使用arr1[i] + arr2[i]方法来查看是否满足您的条件。

arr3[i]

答案 1 :(得分:0)

您可以使用includesfilter

使用include来检查arr1 [i] + arr2 [i]是否是arr3的子字符串,并根据该字符串进行过滤。

let arr1 = ["V1","V1","V1","V1","V1","V2","V2","V2"]
let arr2 = ["A1","A1","B1","B1","B1","A2","A2","A2"]
let arr3 = ["V1A1*","V1A1*","V1B1*","V1B1*", 'just for test']

let op = (arr3.filter((e,i)=>e.includes(arr1[i]+arr2[i])) || [] ).length

console.log(op)

答案 2 :(得分:0)

要获取匹配项和所述匹配项的长度,可以使用filter。假设您想知道每个值的匹配项,而不是匹配项的总和。

for (i=0; i < arr1.length-1; i++) {
  const combinedValue = `${arr1[i]}${arr2[i]}`;
  const matches = arr3.filter(e => e.indexOf(combinedValue) > -1);
  console.log(`Number of matches for ${combinedValue}: ${matches.length}`);
}