根据内容位置合并两个词典

时间:2013-04-13 19:14:47

标签: javascript

我有两个字典,它们记录了同一事件并采取了不同的步骤。

A: [ { tap red }, { tap blue }, { tap green }, { tap commit } ]

B: [ { tap yellow }, { tap blue }, { tap commit } ]

合并应该如下:

[ { tap yellow }, { tap red }, { tap blue }, { tap green }, { tap commit } ]

黄色和红色,并且在蓝色之前在A和B中完成,因此它应该位于{ tap blue }之前,{ tap green }位于{ tap commit }之前,而{ tap commit }始终位于{{1}}之前端。

在JavaScript中实现此功能的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

详细信息取决于您希望它在各种退化情况下的行为方式,但从广义上讲:(粗糙的伪javascript)

var position_B = 0
foreach( A as position_A ) {
    var found_B = B.indexOf( A[position_A], position_B );
    if( found_B !== -1 ) {
        // todo: copy B[position_B] to B[found_B] (inclusive) into Result
        position_B = found_B + 1;
    } else {
        // todo: copy A[position_A] into Result
    }
}
// todo: copy B[position_B] to B[end] (inclusive) into Result

它循环遍历A的所有项目,并且对于每个项目,检查它是否在B中。如果是,它将复制B的最后一个匹配和当前匹配之间的所有项目,否则它只复制A.然后它包括B中的所有内容,到目前为止还没有包括在内。