我有两个数组:
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_old的ID是否存在于array_new中,所以我希望代码在这个例子中输出“5437在array_new中不存在”。
我找不到任何可以让我这样做的功能,所以我应该怎么做?
答案 0 :(得分:1)
http://jsfiddle.net/tppiotrowski/VHb3Q/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(old_index, old_obj) {
var old_id = old_obj['id'];
var found = false;
$.each(array_new, function(new_index, new_obj) {
if (new_obj['id'] == old_id) {
found = true;
}
});
if (!found) {
alert(old_id + " does not exist in array_new");
}
});
答案 1 :(得分:1)
我自己找到了一种方法,但我不知道这是否是最好的方法:
var array_old = [{id: "5436",title: "I Like you boy"},{id: "5437",title: "Hello how are you"},{id: "5438",title: "Hello how are you2"}];
var array_new = [{id: "5436",title: "I Like you boy"},{id: "1132",title: "I'm fine"}];
$.each(array_old, function(id, array){
found = 0;
$.each(array_new, function(id2, array2) {
if(array['id']==array2['id'])
{
found++;
}
});
if(found==0)
{
alert(array['id']+' does not exist in array_new');
}
});
答案 2 :(得分:1)
取决于您的阵列有多大 - 您可能希望使用更高性能的解决方案。
Θ(n*m)
O(n*m)
O(min(n,m))
。如果您需要在此之前对其进行排序,则会获得O(n*log n+m*log m)
。O(1)
查询,从而生成O(n+m)
。您可以轻松地使用JS对象: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]--;
});
(Demo)
答案 3 :(得分:0)
投入一个狂野的替代品只是因为它有效并且最终更容易阅读(不知道性能,但让我们跳过它,因为我这样做是为了展示另一种方式)
var ids_old = $.map(array_old, function(item) { return item.id; });
var ids_new = $.map(array_new, function(item) { return item.id; });
var duplicates = $.grep(ids_old, function(i, id) {
return $.inArray(id, ids_new) !== -1;
});
请注意,最终结果是您获得了重复ID本身的列表,另一种替代方法是让您自己收集项目:
var ids_new = $.map(array_new, function(item) { return item.id; });
var duplicates = $.grep(array_old, function(i, item) {
return $.inArray(item.id, ids_new) !== -1;
});
奖励积分:即使他的示例是纯jQuery,请注意,在ECMAScript5兼容的浏览器上,您可以使用本机阵列对应物来实现相同的结果。