Javascript 考虑数组之间的差异

Javascript 考虑数组之间的差异,javascript,arrays,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

我试图找到一种比较两个数组并返回数组元素差异的快速方法。我想出了一些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 })];
}
/**
*返回两个数组的差
* 
*@param{Array}other,要比较的第二个数组
*@param{Funciton}比较函数,用于比较的回调函数
*@returns{Array}0--仅第一个数组中元素的索引
*1—仅第二个数组中的元素索引
*/
Array.prototype.difference=函数(其他,比较函数){
比较函数=比较函数| |函数(a,b){返回a==b;};
var额外=[],
匹配=[]
元素_found=false;
//与所有值匹配的填充
对于(var_j=0;_j
您正在运行的算法将花费O(n^2)个时间。
最好只对两个数组进行排序,然后以类似于合并的方式找到差异。这需要O(n*logn)时间。

这个问题似乎离题了,因为它属于@feeela。我想要的不仅仅是数组中的额外元素,还有缺少的元素,你提到的问题只有额外元素,我想我不需要检查我的代码,如果我问了一个最好的方法来获得数组之间的差异,而不发布我所拥有的内容,那么这和这个有什么区别呢。。。但是,您需要一种排序方法,对于较短的数组,这不是需要较长的时间吗?您的数组有多短?如果某个数组太小,那么按快速排序(quicksort)进行排序确实需要更长的时间,但在这种情况下,您可以直接通过比较进行排序。您可能会根据数组的长度选择排序算法。但排序仍然会赢得O(n^2)。