Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to compare two arrays with multiple values in each index and remove the duplicate

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>
like image 625
Mark Vincent Manjac Avatar asked Nov 27 '25 23:11

Mark Vincent Manjac


1 Answers

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(','));
});
like image 184
patrick Avatar answered Nov 30 '25 13:11

patrick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!