intersection of n lists via JS

試著忘記壹切 提交于 2019-11-29 12:18:37

Let's say you have an array of lists instead:

var lists = [];
lists[0] = [1, 2, 'b']; 
lists[1] = [2, 'b', 'b'];
lists[2] = [2, 'b', 'c'];
lists[3] = ['a', 'b', 'c'];

Then you can use this:

// say you call this passing the array of lists as the argument: intersect_all(lists)
function intersect_all(lists)
{
    if (lists.length == 0) return [];
    else if (lists.length == 1) return lists[0];

    var partialInt = lists[0];
    for (var i = 1; i < lists.length; i++)
    {
        partialInt = intersection(partialInt, lists[i]);
    }
    return partialInt;
}

The ever useful underscore library has an intersect function, that takes multiple arrays.

http://documentcloud.github.com/underscore/#intersect

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