比较两个不同的数组元素,删除节点js中的匹配元素

时间:2017-05-31 07:05:45

标签: javascript jquery node.js

我有两个数组对象,如下所示:

var arrayOne = [{"Name":"job","SubscriptionGUID":"8ead7edfa460"},{"Name":"TestJobSQL","SubscriptionGUID":"09e7dbff7779"}];
var arrayTwo = [{"UserSubscriptionID":13,"SubscriptionGUID":"8ead7edfa460","Name":"job"}];
var arrayDiff = [];

我需要比较元素名称并删除匹配的元素,只显示 arrayDiff

中不匹配的数组元素

如上例所示我的新 arrayDiff 应为

var arrayDiff = [{"Name":"TestJobSQL"}]; or var arrayDiff = ['TestJobSQL'];

如果 arrayTwo

var arrayTwo = [];

然后 arrayDiff 应该返回

var arrayDiff = [{"Name":"TestJobSQL"},{"Name":"Job"}]; or  var arrayDiff = ['TestJobSQL', 'Job'];

4 个答案:

答案 0 :(得分:1)

试试这个

 <div id='sidebar-nav'>
  ...

  <li style="color:black"><a href='@Url.Action("Desc", 
  "Home",new{id=@obj})'>@obj</li>
  ...

</div>

<div id="div2"></div>


<script type="text/javascript">
    $(function(){
        $("li>a").click(function (e) { 
            e.preventDefault();
            $("#div2").load($(this).attr("href"));
        });
    });
</script>

答案 1 :(得分:0)

一种简单的方法是使用lodash和_.differenceBy方法。

让你根据你想要的属性制作两个数组diff。

答案 2 :(得分:0)

var createDiffArray = function(attrName,arrayOne,arrayTwo){
   var arrayDif = [];
   for (let element of arrayOne){
      if (arrayTwo.find( x => x[attrName] === element[attrName]) !== undefined){
          arrayDif.push(element[attrName]);
      }  
   }
   return arrayDif;
}

答案 3 :(得分:0)

&#13;
&#13;
var arrayOne = [{"Name":"job","SubscriptionGUID":"8ead7edfa460"},{"Name":"TestJobSQL","SubscriptionGUID":"09e7dbff7779"}];
var arrayTwo = [{"UserSubscriptionID":13,"SubscriptionGUID":"8ead7edfa460","Name":"job"}];
//arrayTwo=[];
var result = [];


arrayOne.forEach(function(e){
  if(arrayTwo.length==0){
    result.push(e.Name);
  }else{
  arrayTwo.forEach(function(e2){
    if(e.Name!=e2.Name){
      result.push(e.Name);
    }
  })
  }

})
console.log(result);
&#13;
&#13;
&#13;