Reputation: 25
If I have two array
A = [ "B,C,D"
"W,F,G"
"M,S,E"
]
D = [E]
and want to compare D OR G with E (I mean the third one in each line)and If they are equal can show all the line for me. The third one in each line a part of each line and I want just compare the third one If it is equal show that line have equal variable . I wrote this code but didn't give me the response that I need have :
for(var k=0 ; k<A.length ; k++){
if(A[k].split(",")[2] === E) {
finalSuccessServices = A;
console.log(finalSuccessServices );
}
How can I improve my code to get that line that have my equal variable?
Upvotes: 1
Views: 49
Reputation: 11001
split
and destructure to get third element
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);
Upvotes: 0
Reputation: 33726
You can use the function filter
along with the function includes
in order to select those lines which have a third letter within the array 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);
Upvotes: 0
Reputation: 2530
You can use find()
to get the matching string, provided you have a single match:
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)
Upvotes: 1
Reputation: 386730
You could filter the array and have a look up with 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);
If you need only the first one, take 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);
Upvotes: 0