[英]Remove Duplicates from Jquery
I have two strings like below and I need to remove the duplicates. 我有两个像下面这样的字符串,我需要删除重复项。
IE, I need to remove/ignore the common elements in both the strings and show only the difference. IE,我需要删除/忽略两个字符串中的共同元素,并仅显示差异。
var char1 = "AAA-BBB|BBB-CCC|CCC-AAA";
var char2 = "AAA-BBB|BBB-CCC";
var removeDuplicates = //<-- Here I need CCC-AAA only
Here I have tried it, 我在这里尝试过
var Joined = char1 + "|" + char2;
var removeDuplicates = $.unique(Joined.split('|')); //<-- Result : "AAA-BBB|BBB-CCC|CCC-AAA";
jQuery's $.grep
can be used to remove all duplicates in an array 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>
You can simply make an array from the parameters and Array#filter() the array one returning only the elements that are not in the second array with Array#indexOf() : 您可以使用Array#indexOf()从参数和Array#filter()中简单地创建一个数组,该数组仅返回不在第二个数组中的元素 :
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.