使用浏览器的 Javascript 进行集合对比

有时候要做些集合的对比, 比如集合A有, 集合B 没有之类的, 或者二者都有的. 浏览器的console 是一个很好的工具, 可以用Javascript 来对比.

function onlyInSet1(set1, set2) {
    var onlySet1Has = [];
    for (var i in set1) {
        if (0 > set2.indexOf(set1[i])) {
            onlySet1Has.push(set1[i]);
        }
    }
    
    return onlySet1Has;
}

function inBothSets(set1, set2) {
    var bothHave = [];
    for (var i in set1) {
        if (0 <= set2.indexOf(set1[i])) {
            bothHave.push(set1[i]);
        }
    }
    
    return bothHave;
}

function printSet(set) {
    for (var i in set) {
        console.debug(set[i]);
    }
}

var set1 = ["a", "b", "c", "d"];
var set2 = ["b", "c", "d", "e"];

var onlySet1Has = onlyInSet1(set1, set2);
var onlySet2Has = onlyInSet1(set2, set1);

console.debug("Only Set1 has: ");
printSet(onlySet1Has);

console.debug("Only Set2 has: ");
printSet(onlySet2Has);

var bothHave = inBothSets(set1, set2);
console.debug("Both have: ");
printSet(bothHave);

标签: none

添加新评论