开发者

Javascript: check if an element from an array is found in another array

开发者 https://www.devze.com 2023-02-18 13:28 出处:网络
I have two arrays: var arr1 = [\"1\", \"2\", \"3\"], arr2 = [\"2\", \"5\", \"8\"]; What is the best way to determine if any element from arr1 matches any element in arr2?

I have two arrays:

var arr1 = ["1", "2", "3"],
    arr2 = ["2", "5", "8"];

What is the best way to determine if any element from arr1 matches any element in arr2?

I'm using jquery, so for now I'm looping arr1 and calling $.inArray(arr1[i], arr2); but I'm curious if there's a better way.

Edit

If anyone is curious about my exact case, it's a google map where I'm looping the markers to see if any of the filtered types are found in the types stored with the marker. If any are found, I show the marker. Otherwise it's hidden. [This code works - will test soon with lots of markers]

var filters = $("#map-search :checked").map(function () {
    return this.value;
}).get(),
    markerIndex = 0;

fo开发者_如何学Gor (markerIndex; markerIndex < AKTA.Map.markers.length; markerIndex++) {

    var marker = AKTA.Map.markers[markerIndex],
        isVisible = false;

    if (filters.length > 0) {
        var filterIndex = 0;
        for (filterIndex; filterIndex < filters.length; filterIndex++) {
            if ($.inArray(filters[filterIndex], marker.types) != -1) {
                isVisible = true;
                break;
            }
        }
    }

    marker.setVisible(isVisible);

}


arr1.some(function(el) {
    return arr2.indexOf(el) > -1
});

The MDC provides the following code for browsers that don't implement some:

if (!Array.prototype.some)
{
  Array.prototype.some = function(fun /*, thisp */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in t && fun.call(thisp, t[i], i, t))
        return true;
    }

    return false;
  };
}


Sort both arrays, and after that use this pseudocode:

i=0;
j=0;
while(i<array1length && j<array2length) {
    if (array1[i]<array2[j])
        i++;
    else if (array1[i]>array2[j])
        j++;
    else
        //match!!
}

I think, there is no faster way to do this.

Eventually, if you are matching strings, you may hashcode them first, and match only the hashcodes.

0

精彩评论

暂无评论...
验证码 换一张
取 消