【问题标题】:From two array get unique value in third array in javascript从两个数组在javascript中的第三个数组中获取唯一值
【发布时间】:2013-03-20 07:49:51
【问题描述】:

我有两个 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 is null or not an object”。

【问题讨论】:

  • 您是否要合并两个数组?你为什么要这样做 x[i]

标签: javascript arrays unique


【解决方案1】:
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++;
}
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-31
    • 2022-01-09
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 2023-02-16
    • 1970-01-01
    相关资源
    最近更新 更多