开发者

Compare arrays with jQuery [duplicate]

开发者 https://www.devze.com 2023-03-04 11:45 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicates: Simplest code for array intersection in javascr开发者_开发知识库ipt
This question already has answers here: Closed 11 years ago.

Possible Duplicates:

Simplest code for array intersection in javascr开发者_开发知识库ipt

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.


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


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


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消