开发者

JS List intersection for my use case

开发者 https://www.devze.com 2023-03-31 01:13 出处:网络
I am a javascript newbie so bear with me. I have lists as so: var list1 = [\'a\',\'b\',\'c\']; var list2 = [\'c\',\'d\',\'e\'];

I am a javascript newbie so bear with me. I have lists as so:

var list1 = ['a','b','c'];
var list2 = ['c','d','e'];
var list3 = ['f','g'];

As you see, list1 and list2 intersect at 'c' while list3 is disjoint from both list1 and list2.

The result should be

['a','b','c','d','e'],['f','g'] // Two arrays

We have combined list1 and list2 since they intersect while leaving list3 as is. Another example:

var list1 = ['a','b开发者_C百科','c'];
var list2 = ['d','e','f'];
var list3 = ['f','g','a'];

Here we see list1 and list2 don't intersect, list1 intersects with list3 at 'a' and list2 intersects list3 at 'f'. So since all 3 intersect, the result returned would be:

['a','b','c','d','e','f','g'] // One array

Any help is appreciated

KA

PS: I did search the site for a similar problem and I came across one intersection of n lists via JS Its similar but doesn't serve my use case.


If you have two-list intersection and union functions, you can get what you want with this logic:

var lists; // initialized with the lists you want to process
var merged = [];
for each list a in lists {
    for each list b in merged {
        if intersect(a,b) != empty {
            remove b from merged;
            a = union(a,b);
        }
    }
    add a to merged;
}

You just have to be a little careful about removing b from merged while you are looping through all the elements of merged. It might be simpler to iterate through merged from the last to the first element. The underscore library is a nice place to find functions for intersection and union.


try

<script>
    Array.prototype.unique = function() {  
        var temp = {}, len = this.length;
        for(var i=0; i < len; i++)  {  
            if(typeof temp[this[i]] == "undefined") {
                temp[this[i]] = 1;
            }  
        }  
        this.length = 0;
        len = 0;
        for(var i in temp) {  
            this[len++] = i;
        }  
        return this;  
    }  

    var list1 = ['a','b','c'];
    var list2 = ['c','d','e'];
    var list3 = ['f','g'];


    start = new Date().getTime(); 
    var list = list1.concat(list2).concat(list3).unique(); 
</script>
0

精彩评论

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

关注公众号