TechGuy TechGuy - 16 days ago 7
HTML Question

Remove Duplicates from Jquery

I have two strings like below and I need to remove the duplicates.

I.E., I need to remove/ignore the common elements in both the strings and show only the difference.

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";

Answer

jQuery's $.grep can be used to remove all duplicates in an array

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>

Comments