在JavaScript数组列表获取唯一的共同目标 [英] Get only common objects from a list of arrays in javascript

查看:85
本文介绍了在JavaScript数组列表获取唯一的共同目标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的javascript code一对夫妇阵列(我用的淘汰赛JS太),我想获得一个只包含所有阵列的通用对象单一阵列中。

i have a couple arrays in my javascript code (i'm using knockout js too) and i want to get a single array that contains only the common objects of all the arrays.

我的code是这样的:

My code is something like this:

Array1 = [{a: 1, b: 'something'}, {a: 2, b: 'something1'},{a: 3, b: 'something3'}];

Array2 = [{a: 3, b: 'something3'}, {a: 1, b: 'something'}, {a: 4, b: 'something4'}]

Array2 = [{a: 3, b: 'something3'}, {a: 1, b: 'something'}, {a: 5, b: 'something5'}]

所以,从这个数组我想共同所有到一个单一的阵列,所以结果会是这样:

So, from this arrays i want the common of all into one single array, so the result would be like this:

Array4 = [{a: 1, b: 'something'}, {a: 3, b: 'something3'}]

我要提及的是,数组1,ARRAY2和ARRAY3都是这样另一个数组里面:

I have to mention that the Array1, Array2 and Array3 are inside another array like this:

Array0 = [Array1, Array2, Array3];

我希望你能帮助我,谢谢!

I hope you can help me with this, thank you!

推荐答案

例如:

Array1 = [{a: 1, b: 'something'}, {a: 2, b: 'something1'},{a: 3, b: 'something3'}];
Array2 = [{a: 3, b: 'something3'}, {a: 1, b: 'something'}, {a: 4, b: 'something4'}]
Array3 = [{a: 3, b: 'something3'}, {a: 1, b: 'something'}, {a: 5, b: 'something5'}]

all = [Array1, Array2, Array3]

objects = {}
counter = {}

all.map(function(ary, n) {
    ary.map(function(obj) {
        var key = JSON.stringify(obj);
        objects[key] = obj;
        counter[key] = (counter[key] || 0) | (1 << n);
    })
})

intersection = []
Object.keys(counter).map(function(key) {
    if(counter[key] == (1 << all.length) - 1)
        intersection.push(objects[key]);
})

console.log(intersection)

我们的想法是把所有的物体在哈希表中使用他们的JSON重新presentations作为键。

The idea is to put all objects in a hash table using their JSON representations as keys.

这篇关于在JavaScript数组列表获取唯一的共同目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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