I have two arrays, and I want to be able to compare the two and only return the values that match. For example both arrays have the value cat so that is what will be returned. I haven’t found anything like this. What would be the best way to return similarities?
var array1 = ["cat", "sum","fun", "run"];
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];
//if value in array1 is equal to value in array2 then return match: cat
Naturally, my approach was to loop through the first array once and check the index of each value in the second array. If the index is
> -1, thenpushit onto the returned array.
My solution doesn’t use two loops like others do so it may run a bit faster. If you want to avoid using
for..in, you can sort both arrays first to reindex all their values:Usage would look like:
If you have an issue/problem with extending the Array prototype, you could easily change this to a function.
And you’d change anywhere where the func originally said
thistoarr2.