0

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";
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
TechGuy
  • 4,298
  • 15
  • 56
  • 87
  • So, you need to remove duplicates from a list of strings after this string is split by the `|` char? – marcusshep Nov 16 '16 at 16:07
  • 3
    [From `$.unique()` docs](https://api.jquery.com/jQuery.unique/): *Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, **not strings or numbers.*** – DontVoteMeDown Nov 16 '16 at 16:08
  • http://stackoverflow.com/a/9229784/3569921 – marcusshep Nov 16 '16 at 16:08
  • Yes.Lets say your string is A,B,B,C,D,D then i need my result is : A,C only – TechGuy Nov 16 '16 at 16:08
  • Oh, so if string has duplicates, remove all instances of that string. – marcusshep Nov 16 '16 at 16:09
  • Check out http://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript for array intersection – Eric Nov 16 '16 at 16:12

2 Answers2

3

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>
adeneo
  • 312,895
  • 29
  • 395
  • 388
1

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():

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));
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46