区分数组

时间:2014-06-20 22:46:25

标签: javascript arrays

我正在尝试找到一种比较两个数组并返回数组元素差异的快速方法。我想出了一些N2,但是有更多的循环,有更好的方法吗?

/**
* Return the difference of two arrays
* 
* @param {Array} other, the second array to be compared
* @param {Funciton} comparison_function, callback function for comparisons
* @returns {Array} 0 -- indexes of elements only in the first array 
*                  1 -- indexes of elements only in the second array
*/
Array.prototype.difference = function(other, comparison_function){
    comparison_function = comparison_function || function(a,b){ return a == b;};
    var extra = [],
        matched = []
        element_found = false;
    // fill matched with all values
    for(var _j = 0; _j < other.length; _j++){matched.push(_j);}
    for(var _i = 0; _i < this.length; _i++){
        element_found = false;
        for(var _j = 0; _j < other.length; _j++){
            if(comparison_function(this[_i], other[_j])){
                matched[_j] = undefined;
                element_found = true;
                break;
            }
        }
        if(!element_found) extra.push(_i);
    }
    return [extra, matched.filter(function(x){ return x !== undefined })];
}

1 个答案:

答案 0 :(得分:0)

您运行的算法需要O(n ^ 2)时间。 只需对两个数组进行排序,然后以类似于合并的方式找到差异,效果会好得多。这将花费O(n * logn)时间。