3

I really don't know how to do this. I want to remove the duplicate value of an array that has a multiple value. I tried to use the code from this post Compare arrays with jQuery [duplicate] but i didn't get the result i want. Please help me with this.

var arr1 = ["1,2,3", "4,5", "6", "7,8", "9,10"];
var arr2 = ["2", "4", "7,8"];
var result = []; //expected output: Array["1,3","5","6","9,10"]

$.each(arr1, function(i, val) {
  if ($.inArray(val, arr2) < 0)
    result.push(val);
});
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Community
  • 1
  • 1
Mark Vincent Manjac
  • 507
  • 1
  • 6
  • 27
  • 2
    On both array, did you voluntary forget the double quote between the comma or the ``arr1[]`` (for example) should be like ``"1","2","3","4","5"...`` ? – Zachary Dahan May 04 '15 at 01:39
  • No sir, I intended it to be that way. The array will have multiple values in each index separated by comma. then using `.split()` i can make the value of each index into an array. – Mark Vincent Manjac May 04 '15 at 01:43
  • In your example, what result would you expect if `arr2` also contained "1"? (If two different arr2 items are present in a string, are they both removed?) What if it didn't contain "2", but did contain "1,3"? (If arr2 has a an item with two numbers separated by a comma, do they have to appear next to each other to be removed, or anywhere in the string?) – S McCrohan May 04 '15 at 02:03

2 Answers2

3

If performance is not a huge concern, this will do what you need:

var arr1   = ["1,2,3", "4,5", "6", "7,8", "9,10"]
var arr2   = ["2", "4", "7,8"].join(',').split(',');
var result = [];

$.each(arr1, function(i, val) {
  var values   = val.split(',');
  var filtered = [];
  $.each(values, function (i, value) {
    if ($.inArray(value, arr2) === -1) {
      filtered.push(value);
    }
  });

  if (filtered.length) result.push(filtered.join(','));
});
patrick
  • 9,290
  • 13
  • 61
  • 112
0

First things first, you're going to have to split each of the number strings up and add them to an array as integers.

After that, you'll probably want to use something like a hash map to efficiently get the intersect of the arrays. This example should do the job.

Here's a simple example. Of course, you would also need to split arr2 + add its values to intersectMap

intersectMap = {}
for (i = 0; i < arr.length; i++) {
    var values = arr[1].split(",")
    // add these values to a hash map
    for (j = 0; j < values.length; j++) {
        intersectMap[values[j]] = values[j]
    }
}

You will basically want to run through each of the arrays you just created (with the properly split strings), add them to a hash map (intersectMap), and upon completion, add all keys to a new array. This will guarantee that you end up with an array of unique values in the most efficient time possible.

Jed Fox
  • 2,979
  • 5
  • 28
  • 38
grill
  • 1,160
  • 1
  • 11
  • 24