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>
2

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Is there also a way to exclude instead of include?
@emred Yes just use ! before some() ... array2.filter(x => !array1.some(a => x.includes(a)));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.