2013-03-20 51 views
0

我有兩個JavaScript數組對象像下面從兩個陣列獲得第三組獨特的價值在javascript

第一陣列:

count_array[0].left= 0; 
count_array[0].width= 33; 
count_array[0].id= 1; 
count_array[1].left= ""; 
count_array[1].width= ""; 
count_array[1].id= 2; 
count_array[2].left= ""; 
count_array[2].width= ""; 
count_array[2].id= 3; 

二陣:

temp_array[0].left= ""; 
temp_array[0].width= ""; 
temp_array[0].id= 4; 
temp_array[1].left= ""; 
temp_array[1].width= ""; 
temp_array[1].id= 5; 
temp_array[2].left= 0; 
temp_array[2].width= 33; 
temp_array[2].id= 1; 

我想從上面的兩個數組中獲得的javascript中id的唯一值的數組,如下所示

第三個數組:

temp_array_cnt[0].left= 0; 
temp_array_cnt[0].width= 33; 
temp_array_cnt[0].id= 1; 

我使用下面的代碼,但它不工作

function intersection(x,y){ 
    x.sort();y.sort(); 
var i=j=0;ret=[]; 
while(i<x.length && j<y.length){ 
    if(x[i]<y[j])i++; 
    else if(y[j]<x[i])j++; 
    else { 
    ret.push(x[i]); 
    i++,j++; 
    } 
    } 
return ret; 

}

請幫我在這裏。 感謝

我使用下面的函數現在

function intersection(x,y){ 
ret=[]; 
//x.sort();y.sort(); 
for(var i=0;i<x.length;i++) 
{ 
for(var j=0;j<y.length;i++) 
{ 
    //console.log(x[i].eventid); 
    var chk_left=x[i]; 
    if(chk_left.id == chk_left.id) 
    { 
     ret.push(chk_left); 
    } 
} 
} 
    return ret; 
    } 

但它給我的錯誤這樣的「ID爲空或不是對象」。

+0

你想要結合兩個數組?爲什麼你這樣做x [i] 2013-03-20 07:57:04

回答

0
var temp = 0; 

for(var i=0;i<count_array.length;i++) 
{ 
for(var j=0;j<temp_array.length;i++) 
{ 
if(count_array[i].id == temp_array[j].id) 
{ 
temp_array_cnt[temp].left= count_array[i].left; 
temp_array_cnt[temp].width= count_array[i].width; 
temp_array_cnt[temp].id= count_array[i].id; 
temp++; 
} 
} 
}