Compare arrays with jQuery [duplicate]

北城余情 提交于 2019-12-11 10:32:49

问题


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.


回答1:


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




回答2:


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



回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/5916296/compare-arrays-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!