JS计算2个对象中的差异#

时间:2014-08-20 15:14:00

标签: javascript algorithm object

我试图比较2个对象并返回数组中不同元素的#。
最初我想的是首先按对象长度对对象进行排序,然后从maxLength中读取。但后来我注意到min-length对象也可能包含一些唯一的键。例如

var max_obj = { a: aa, b: bb, c: cc, d: dd }
var min_obj = { a: aa, b: bb, z: zz }

所以我再次在min_obj中循环任何缺失的键,但随着对象的扩展,它似乎很糟糕(仍然是O(n)但是图像中有100000个键?)。所以代码看起来像这样:

// innerLength: count # of diff in a specific object key
// maxObj/minObj: originally I sort them by key.length, but from this point this seems useless
      for(var t in maxObj) {
            if (!(t in minObj)) {
                diffCount += innerLength(maxObj[t]);
            } else if (!elementEqualFn(maxObj[t], minObj[t])) {
                diffCount += Math.abs(innerLength(maxObj[t]) - innerLength(minObj[t]));;
            } 
        } 
        // inefficient, but we need to count those unique ones in minObj as well
        for(var t in minObj) {
            if (!(t in maxObj)) {
                diffCount += innertLength(minObj[t]);
            }
        }

有没有人对此有任何建议/想法?

1 个答案:

答案 0 :(得分:0)

由于你必须检查每一把钥匙,我相信你不能更快地完成它。

相关问题