如何比较每行中每个数组中的第三个



如果我有两个数组

A = [ "B,C,D"
"W,F,G"
"M,S,E"
]
D = [E]

并且想要将DG与E(我指的是每行中的第三个(进行比较,如果它们相等,可以为我显示所有行。每行中第三个是每行的一部分,我只想比较第三个如果相等,则表明该行具有相等的变量。我写了这个代码,但没有给我需要的回应:

for(var k=0 ; k<A.length ; k++){
if(A[k].split(",")[2] === E) {
finalSuccessServices = A;
console.log(finalSuccessServices );
}

如何改进我的代码以获得具有相等变量的行?

您可以使用find()来获取匹配字符串,前提是您只有一个匹配项:

const A = [ "B,C,D",
"W,F,G",
"M,S,E"
];
const D = ['E'];
let result = A.find(str => str.split(',')[2] === D[0]);
console.log(result)

您可以过滤数组并查找includes

var array = ["B,C,D", "W,F,G", "M,S,E"],
pattern = ['E'],
result = array.filter(s => pattern.includes(s.split(',')[2]));
console.log(result);

如果您只需要第一个,请服用find

var array = ["B,C,D", "W,F,G", "M,S,E"],
pattern = ['E'],
result = array.find(s => pattern.includes(s.split(',')[2]));
console.log(result);

您可以使用函数filter和函数includes来选择数组D中具有第三个字母的行。

let A = [ "B,C,D", "W,F,G", "M,S,E" ],
D = ["E"],
result = A.filter(s => {
let [,,C] = s.split(",");
return D.includes(C);
});

console.log(result);

  1. 使用split和析构函数获取第三个元素
  2. 比较第三个值和第一个值(来自数组D(
  3. 控制台日志并推送到finalSuccessServices数组

const A = ["B,C,D", "W,F,G", "M,S,E"];
const D = ["E"];
const [first] = D;
const finalSuccessServices = [];
A.forEach(line => {
const [,, third] = line.split(",");
if (third === first) {
console.log(line);
finalSuccessServices.push(line);
}
});
console.log("finalSuccessServices", finalSuccessServices);

相关内容

  • 没有找到相关文章

最新更新