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.

+1


source to share


4 answers


You can do it:

var items = Array(523,3452,334,31,5346);
var items_used = Array(3452,31,4123);
var items_compared = Array();

    $.each(items, function(i, val){
      if($.inArray(val, items_used) < 0)
          items_compared.push(val);
    });

      



What he

+6


source


Why not a simple loop?



for(var j = 0; j < items.length; j++)
{
    var found = false;
    for(var k = 0; k < items_used.length; k++)
    {
       if(items_used[k] == items[j])
       {
           found = true;
           break;
       }
    }

    if(!found)
       items_compared.push(items[j]);
}

      

+4


source


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.

+1


source


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);
}

      

0


source







All Articles