網頁

2010年3月14日星期日

Javascript - Array difference

以下Function用途是比對兩段Array,找出不同的元素。
function diffArrays(arr1, arr2, returnUnion) {
    var ret = [];
    var test = {};
    var bigArray, smallArray, key;
    if (arr1.length >= arr2.length) {
        bigArray = arr1;
        smallArray = arr2;
    } else {
        bigArray = arr2;
        smallArray = arr1;
    }
    for (var i = 0; i < bigArray.length; i++) {
        key = bigArray[i];
        test[key] = true;
    }
    if (!returnUnion) {
        //diffing
        for (var i = 0; i < smallArray.length; i++) {
            key = smallArray[i];
            if (!test[key]) {
                test[key] = null;
            }
        }
    } else {
        //union
        for (var i = 0; i < smallArray.length; i++) {
            key = smallArray[i];
            if (!test[key]) {
                test[key] = true;
            }
        }
    }
    for (var i in test) {
        ret.push(i);
    }
    return ret;
} 
array1 = "test1", "test2", "test3", "test4", "test7"
array2 = "test1", "test2", "test3", "test4", "test5", "test6"
diffArray = diffArrays(array1, array2);
//returns ["test5","test6","test7"]
 
diffArray = diffArrays(array1, array2, true);
//returns ["test1", "test2","test3","test4", "test5", "test6","test7"]

沒有留言:

發佈留言