从Jquery中删除重复项

时间:2016-11-16 16:06:16

标签: javascript jquery html

我有两个字符串,如下所示,我需要删除重复项。

I.E。,我需要删除/忽略两个字符串中的公共元素,并仅显示差异。

var char1 = "AAA-BBB|BBB-CCC|CCC-AAA";
var char2 = "AAA-BBB|BBB-CCC";
var removeDuplicates = //<-- Here I need CCC-AAA only

我在这里尝试过,

 var Joined = char1 + "|" + char2;
 var removeDuplicates = $.unique(Joined.split('|')); //<-- Result : "AAA-BBB|BBB-CCC|CCC-AAA";

2 个答案:

答案 0 :(得分:3)

jQuery的$.grep可用于删除数组中的所有重复项

var char1 = "AAA-BBB|BBB-CCC|CCC-AAA";
var char2 = "AAA-BBB|BBB-CCC";

var removeDuplicates = $.grep(char1.split('|'), (function(y) {
	return function(item) { return $.inArray(item, y) === -1 }
})(char2.split('|')));

console.log( removeDuplicates );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:1)

你可以简单地从参数和Array#filter()数组中创建一个数组,只返回第二个数组中不包含Array#indexOf()的元素:

&#13;
&#13;
var char1 = "AAA-BBB|BBB-CCC|CCC-AAA",
    char2 = "AAA-BBB|BBB-CCC",
    removeDuplicates = function(str1, str2) {
      var arr1 = str1.split('|'),
          arr2 = str2.split('|');
      return arr1.filter(function(item) {
        return arr2.indexOf(item) === -1;
      });
    };

console.log(removeDuplicates(char1, char2));
&#13;
&#13;
&#13;