I want to compare 2 arrays and find the matching values from it, ideally this question has been asked before and seems like it partially works in my case.
lets say I have:
var array1 = ["test-123", "id-859","hi-8098", "hello-9090"];
var array2= ["Welcome <span>test-123</span>", "Welcome33 <span>id-859</span>","How are you <span>hi-8098</span>", "Geat <span>hello-9090</span>", "see ya <span>nono-58758</span>"];
In my case I have html element span and I want to match the values that are inside the <span> and return as o/p:
var newArray= ["Welcome", "Welcome33 ","How are you ", "Geat "];
so basically the values inside array1 matches to all the values inside array2 except the last one"see ya <span>nono-58758</span>". Using filter I can get the matching values, but these values are pretty straight forward,
newArray = array1.filter(e => array2.indexOf(e) !== -1); // in my case its undefined, as it does not recognize the html element in it.
any ideas on how to get matching values when an html element is present inside an array? Thanks!
this works too
var array1 = ["test-123", "id-859","hi-8098", "hello-9090"];
var array2= ["Welcome <span>test-123</span>", "Welcome33 <span>id-859</span>","How are you <span>hi-8098</span>", "Geat <span>hello-9090</span>", "see ya <span>nono-58758</span>"];
var k=[];
array2.forEach(a=>{
array1.forEach(b=>{
if(a.indexOf(b)!=-1){
k.push(a);
}
})
})
let j=k.reduce((o,a)=>{
let i= a.split("<span>");
o.push(i[0]);
return o;
},[])
console.log(j)
indexOf don't use with Array but String . So you need to make string first
var array1 = ["test-123", "id-859","hi-8098", "hello-9090"];
var array2= ["Welcome <span>test-123</span>", "Welcome33 <span>id-859</span>","How are you <span>hi-8098</span>", "Geat <span>hello-9090</span>", "see ya <span>nono-58758</span>"];
var newArr =[];
for(var i of array1) {
for(var j of array2) {
var split = j.split("<span>");
if(split[1].indexOf(i) > -1) {
newArr.push(split[0]);
}
}
}
//newArray = array1.filter(e => array2.indexOf(e) != -1);you don't need this
console.log(newArr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With