JQuery: how to compare two arrays with multiple values at each index and remove duplicate
I really don't know how to do this. I want to remove a duplicate value of an array with multiple values. I tried using 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>
source to share
If performance isn't a big 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(','));
});
source to share
First of all, you will have to split each of the number strings and add them to the array as integers.
After that, you probably want to use something like a hashmap to get the intersection of the arrays efficiently. This example should do the job.
Here's a simple example. Of course, you also need to split arr2 + add your 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]
}
}
Basically you want to run each of the arrays you create (with properly separated strings), add them to a hashmap (intersectMap), and when done add all the keys to a new array. This ensures that you get an array of unique values in the most efficient time possible.
source to share