0

我使用比较两个数组的标准方法,但它就像做标准 O(n^2) 一样慢你们能看到问题吗?

    diffArray: function (arr1, arr2, observableArray, mapping) {
        //We cant sort orginal arrays
        var o = arr1.slice(0);
        var n = arr2.slice(0);

        // sort both arrays (or this won't work)
        var sorter = function (left, right) {
            return mapping.key(left) - mapping.key(right);
        };
        o.sort(sorter); n.sort(sorter);

        // declare temporary variables
        var op = 0; var np = 0;
        var added = []; var removed = [];

        // compare arrays and add to add or remove lists
        while (op < o.length && np < n.length) {
            if (mapping.key(o[op]) < mapping.key(n[np])) {
                // push to diff?
                removed.push(o[op]);
                op++;
            }
            else if (mapping.key(o[op]) > mapping.key(n[np])) {
                // push to diff?
                added.push(n[np]);
                np++;
            }
            else {
                this.diffMembers(o[op], n[np]);
                op++; np++;
            }
        }

        // add remaining items
        if (np < n.length)
            added = added.concat(n.slice(np, n.length));
        if (op < o.length)
            removed = removed.concat(o.slice(op, o.length));

        ko.utils.arrayForEach(removed, function (item) {
            this.itemDeleted(item, mapping);
        }.bind(this));


        ko.utils.arrayForEach(added, function (item) {
            if (observableArray.concurrencyExtendOptions) {
                this.itemAdded(observableArray, item, mapping);
            }
        } .bind(this));
    }

注意:映射对象只是用户提供的用于比较数组中对象的辅助对象,arr1 和 arr2 是标准 JS 数组,而 observableArray 是未包装的 Knockout 数组

它基于 C# 代码示例,所以也许 JS 中的排序算法不是那么好?

4

1 回答 1

1

真的不确定它会回答你,但这是diff我用于数组的:

Array.prototype.diff = function( arr ) {
    return arr.map( function( v ) {
        if ( !~this.indexOf( v ) ) return v;
    }, this ).filter( Boolean );
};

用法:

arr.diff( otherArr );

PS:作为评论发布太长......不确定它是否值得回答。
PS2:函数原作者:@Esailija

于 2012-06-19T08:37:27.630 回答