Comparing arrays with jQuery
Possible duplicates:
Simplest code to intersect an array in javascript
How to concatenate two arrays in Javascript
There are three arrays:
var items = Array(523,3452,334,31,5346);
var items_used = Array(3452,31,4123);
var items_new = Array();
The first is general, the second is the elements used at that time. The third includes all elements from the first array that are not mentioned in the second.
How to remove from the first array elements that are used in the second and write the result to the third array?
We must receive items_new = Array(523, 334, 5346)
. 3452
and 31
removed as they are referenced in the second array.
source to share
A faster solution might be:
var j, itemsHash = {};
for (j = 0; j < items.length; j++) {
itemsHash[items[j]] = true;
}
for (j = 0; j < itemsUsed.length; j++) {
itemsHash[itemsUsed[j]] = false;
}
for (j in itemsHash) {
if (itemsHash[j]) {
itemsCompared.push(j);
}
}
runs in O (n) time with less memory.
source to share
Basically I would do the third, all the elements in the first, and then loop through the second array, removing all those elements found in the first.
var items_compared = items;
for(int i = 0; i < items_used.length; ++i)
{
var indx = $.inArray(items_used[i], items_compared);
if(indx != -1)
items_compared.splice(indx, 1);
}
source to share