不同长度阵列比较后从阵列中删除元素

时间:2018-02-11 13:02:50

标签: jquery arrays

我有两个数组:

allLabBranches = {0:{labbranchid: "1", labname: "Main Branch"}, 1 :{labbranchid: "2", labname: "Gulberg branch"}, 2: {labbranchid: "3", labname: "Shahdara Branch"}};

admnuserbrnchs = {0: 1, 1: 2};

我想删除那些id与admnuserbrnchs元素的元素不匹配的分支。我目前的代码如下:

if(allLabBranches.length >= admnuserbrnchs.length ){
    for(var i =0; i < allLabBranches.length; i++){
        for(var j =0; j < admnuserbrnchs.length; j++){
            if(allLabBranches[i].labbranchid != admnuserbrnchs[j]){

                allLabBranches.splice(i, 1);
            }
        }
    }
}

但是,结果是错误的。

1 个答案:

答案 0 :(得分:0)

您可以使用.filter.includes来实现此目标。

&#13;
&#13;
var allLabBranches = {
  0: {
    labbranchid: "1",
    labname: "Main Branch"
  },
  1: {
    labbranchid: "2",
    labname: "Gulberg branch"
  },
  2: {
    labbranchid: "3",
    labname: "Shahdara Branch"
  }
};
var admnuserbrnchs = {
  0: 1,
  1: 2
};

//Convert the objects to arrays
allLabBranches = Object.values(allLabBranches);
admnuserbrnchs = Object.values(admnuserbrnchs);

//Filter array
var newBranches = allLabBranches.filter(function(v, i) {
  return admnuserbrnchs.includes(Number(v.labbranchid)) ? true : false
});

console.log(newBranches);
&#13;
&#13;
&#13;