1

I'm trying to make this script where I can fill in words in array1 that I want to be filtered out of array2. So I want to get a new array with only the words in array2 that don't contain any value from array1.

This is what I have right now, but it isn't working properly because the loop goes trough it multiple times and in the end every words gets in it multiple times. Now that I have 3 values in array1 every word will be checked 3 times, so in the end every word will make it to the final array. I filtered out duplicate words to

Does anyone have a solution to this? JS fiddle link: https://jsfiddle.net/45z1mpqo/

var array2 = ["January", "February", "March", "April", "May", "June"]
var array1 = ["uary", "May", "December"];
var notMatched = [];
let counter = 0;

for(var b = 0; b < array1.length; b++) {

    for(var i = 0; i < array2.length; i++) {

      if(array2[i].indexOf(array1[b]) != -1)
        { 
        //console.log(stringxa[i]);
        }
        else{
        notMatched[counter] = array2[i];
        counter++;
        }
    }
}
//this filter will remove duplicate elements from array
var unique = notMatched.filter(function(elem, index, self) {
    return index == self.indexOf(elem);
});
document.getElementById("text").innerHTML = unique;


<p id='text'>hi</p>
janjte
  • 43
  • 1
  • 4
  • possible duplicate of https://stackoverflow.com/questions/1723168/what-is-the-fastest-or-most-elegant-way-to-compute-a-set-difference-using-javasc – yunzen May 06 '19 at 09:15
  • Possible duplicate of [What is the fastest or most elegant way to compute a set difference using Javascript arrays?](https://stackoverflow.com/questions/1723168/what-is-the-fastest-or-most-elegant-way-to-compute-a-set-difference-using-javasc) – yunzen May 06 '19 at 09:23

1 Answers1

1

You can use filter() on array2 and check if any of the value of the array1 is included in the string using some()

var array2 = ["January", "February", "March", "April", "May", "June"]
var array1 = ["uary", "May", "December"];


let res = array2.filter(x => array1.some(a => x.includes(a)));

console.log(res)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73