如何找到在数组2不在数组1元素? [英] How to find elements in array2 that are not in array1?

查看:126
本文介绍了如何找到在数组2不在数组1元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组:

var a1 = [ { ID: 2, N:0 }, { ID: 1, N:0 } ];
var a2 = [ { ID: 1, N:0 }, { ID: 2, N:0 }, { ID: 3, N:0 } ];

我需要的是在 A2 的所有元素,但不是在 A1 。这里的元素只能通过 ID ,其他的属性应该被忽略的属性是不同的另一回事。我不能保证在数组中元素的顺序。这意味着结果这个例子应该是:

I need to get all elements that are on a2 but not in a1. An element here is distinct of another only by the property ID, the other properties should be ignored. And I cannot guarantee the order of the elements on the arrays. Meaning the result for this example should be:

var result = [ { ID: 3, N:0 } ]; // result for the example above

我怎么能做到这一点的一种有效的方式? (我将比较阵列500至5000的长度)

How can I do this in an efficient way? (I will be comparing arrays from 500 to 5,000 length)

推荐答案

要有效地做到这一点,你需要建立一个已经在A1项目的索引,所以你可以循环A2和每一个比较索引看它是否已经看到或没有。可以使用一个JavaScript对象的索引。至A1,并把所有的ID添加到索引周期。然后通过A2周期,并收集他们的ID不会出现在索引中的任何项目。

To do this efficiently, you need to build an index of the items that are already in a1 so you can cycle through a2 and compare each one to the index to see if it's already been seen or not. One can use a javascript object for an index. Cycle through a1 and put all its IDs into the index. Then cycle through a2 and collect any items whose ID does not appear in the index.

function findUniques(testItems, baseItems) {
    var index = {}, i;
    var result = [];

    // put baseItems id values into the index
    for (i = 0; i < baseItems.length; i++) {
        index[baseItems[i].ID] = true;
    }

    // now go through the testItems and collect the items in it 
    // that are not in the index
    for (i = 0; i < testItems.length; i++) {
        if (!(testItems[i].ID in index)) {
            result.push(testItems[i]);
        }
    }
    return(result);
}

var a1 = [ { ID: 2, N:0 }, { ID: 1, N:0 } ];
var a2 = [ { ID: 1, N:0 }, { ID: 2, N:0 }, { ID: 3, N:0 } ];

var result = findUniques(a2, a1);
// [{"ID":3,"N":0}]

工作演示: http://jsfiddle.net/jfriend00/uDEtg/

这篇关于如何找到在数组2不在数组1元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆