3

Possible Duplicates:
Simplest code for array intersection in javascript
How to merge 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();

First one is general, second is the items currenly in use. Third one includes all the items from the first array, witch are not mentioned in second.

How do I remove from the first array items, witch are used in second, and write the result to the third array?

We should get items_new = Array(523, 334, 5346). 3452 and 31 are removed, because they are mentioned in second array.

Community
  • 1
  • 1
James
  • 42,081
  • 53
  • 136
  • 161

4 Answers4

6

You could do this:

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

That's it

Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61
4

Why not a simple for 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]);
}
Tejs
  • 40,736
  • 10
  • 68
  • 86
1

As a faster solution maybe :

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 a little more memory.

jesse reiss
  • 4,509
  • 1
  • 20
  • 19
0

Basically I would make the third have all elements in the first, then loop through the second array removing all of 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);
}
Chad
  • 19,219
  • 4
  • 50
  • 73