取数组之间的差值
Taking difference between 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 })];
}
您正在运行的算法将花费O(n^2)时间。最好是对两个数组进行排序,然后用类似于归并的方法找出差异。这需要O(n*logn)时间
相关文章:
- 在 JavaScript 数组中的所有元素之间穿插元素的简洁方法
- 效率:整数数组的一个子集中两个项之间的最大差值
- 使用Javascript获取两个字符串之间的字符串数组
- 如何将json文件中的数据提取到对象数组中,并在两个控制器之间共享
- 尝试在一个对象的值和一个对象数组之间进行匹配
- 在angularJS中使用模态窗口时,在控制器之间共享对象数组
- 无法在提交之间清空数组
- 使用工厂/服务在控制器AngularJS之间推送数组中的数据
- 数组和ArrayBuffer之间的区别是什么
- 只有一些带undercore.js的字段在对象数组之间求交集和等于
- 如何在数组中循环,等待每个项目之间的时间
- 在数组中的偶数之间插入连字符
- 创建新数组和清除长度之间的差异
- 如何循环数组并保持它们之间的索引增长
- for(数组中的i)和for(var i=0;i<array.length;i++)之间的差异
- 在javascript数组元素之间添加换行符
- 我如何获得 Javascript 中关联数组和常规数组之间的区别
- 如何确定数组中的值是否位于两个附加数组的所有并行索引的值之间
- 数组值和字符串之间的 JavaScript 比较
- AngularJS控制器语法 - 数组和函数版本之间的差异