Tuesday | 03 DEC 2024
[ previous ]
[ next ]

Javascript Intersection of Two Arrays

Title:
Date: 2022-01-21
Tags:  

This is quickly becoming a place where I just reinforce my own learning. I stumbled into writing the intersection of two arrays or something I call the any operation. I'll write it down here so that should I need it in the future, I can come back and use this as my example.

const sources = ["url1", "url2", "url3"];
const domains = ["domain1", "domain2", "domain3"];
let validSources = sources.filter(source => domains.some(domain => source.indexOf(domain) !== -1))

The goal is to check if an array shares either entire elements or substrings with another array. We can run a filter on the main array we are checking, and then we can then use the some function on the second array to check if an element from the second array is in the element of the first array.

The some function returns true if the conditional function is true for any element in the array. This way we can then use this function to filter the array so that we only keep elements that are common in both arrays.

const sources = "url";
const domains = ["domain1", "domain2", "domain3"];
if (domains.some(domain => source.indexOf(domain) !== -1)) {
}

This version will check a string has any of the domain substrings in it. This is also helpful when you want to check if a string contains an array of substrings. You can also use the every function here to check if a string contains all the domain substrings.

I do wish there was some syntactic sugar here where all you need to do is something like .any(function). It wouldn't be difficult to write but I also don't want to have a utility file that I include in every project.