比较在JavaScript 2多维数组 [英] Compare two multidimensional arrays in javascript
本文介绍了比较在JavaScript 2多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个数组:
var array_old = [{id:"5436", title:"I Like you boy"}, {id:"5437", title:"Hello how are you"}];
var array_new = [{id:"5436", title:"I Like you boy"}, {id:"1132", title:"I'm fine"}];
$.each(array_old, function(id, array)
{
if(!$.inArray(array['id'], array_new, 1)>-1){
alert(array['id'] + " does not exist in array_new");
}
});
我要检查如果array_new存在array_old的ID,所以我在这个例子中期待code输出5437中array_new不存在。
I want to check if the IDs of array_old exist in array_new, so I'm expecting the code to output "5437 does not exist in array_new" in this example.
我找不到可以让我做的任何功能,所以我应该怎么办呢?
I can't find any function that would allow me to do that, so how should I do it?
推荐答案
取决于如何大的阵列 - 你可能想使用更高性能的解决方案。
Depends on how big your arrays are - you might want to use a more performant solution.
- 最简单的方法(这你和@Tebb找到)具有
Θ(N * M)
- 如果您将优化这一点(打破了,如果你没[不]研究发现元素 - 见@gonchuki),你仍然在
O(N * M)
- 您可以假设两个数组都是以相同的顺序,并且只运行一个循环:
O(分钟(N,M))
。如果你需要在这之前给他们排序,你会得到O(N *登录N + M *日志M)
。 - 最好将使用一个哈希表
O(1)
查找,致使O(N + M)
。您可以轻松地使用JS对象为:
- The easiest solution (which both you and @Tebb found) has
Θ(n*m)
- If you would optimize this a bit (breaking out if you did [not] found the element - see @gonchuki), you are still at
O(n*m)
- You could assume that both arrays are in the same order, and run only one loop:
O(min(n,m))
. If you'd need to sort them before that, you'd getO(n*log n+m*log m)
. - Best would be using a hash table for
O(1)
lookup, resulting inO(n+m)
. You can easily use a JS object for that:
var counts = {};
for (var i=0; i<array_new.length; i++)
counts[array_new[i].id] = (counts[array_new[i].id] || 0) + 1;
return array_old.every(function(item) {
return item.id in counts && counts[item.id]--;
});
(演示)
这篇关于比较在JavaScript 2多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文