Reputation: 505
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>
Upvotes: 3
Views: 1772
Reputation: 1170
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.
Upvotes: 0
Reputation: 9742
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(','));
});
Upvotes: 3