JSFiddle - React, Tailwind, and code Playground
by yairamon
HTML
<h2>list 1</h2>
<textarea id=t1 rows=4 cols=50
oninput="compare()"
placeholder = "list items in any order, separated by spaces or commas"
> </textarea>
<h2>list 2</h2>
<textarea id=t2 rows=4 cols=50
oninput="compare()"
placeholder = "list items in any order, separated by spaces or commas"
> </textarea>
<h2>
In Common
</h2>
<textarea id=t3 rows=4 cols=50
oninput="compare()"
placeholder = "list items in any order, separated by spaces or commas"
> </textarea>
JavaScript
var list1 = document.getElementById("t1");
var list2 = document.getElementById("t2");
var list3 = document.getElementById("t3");
function getWords(para)
{
return(para.split(/[\W]/));
}
function getUniqueWords(para)
{
let set = new Set();
arr = getWords(para);
for (var word of arr) {
if (word.match(/[\w]/) )
set.add(word.toLowerCase());
}
return set;
}
function compare()
{
set1 = getUniqueWords(t1.value);
set2 = getUniqueWords(t2.value);
inCommon = Array.from(intersection(set1, set2).keys());
console.log(inCommon);
list3.value = inCommon.toString();
}
//-----
function intersection(set1, set2)
{
// creating new set to store intersection
var intersectionSet = new Set();
// Iterate over the values
for(var elem of set2)
{
// if the other set contains a
// similar value as of value[i]
// then add it to intersectionSet
if(set1.has(elem))
intersectionSet.add(elem);
}
// return values of intersectionSet
return intersectionSet;
}