Algorithm to get changes between two arrays

后端 未结 8 1374
难免孤独
难免孤独 2021-02-04 05:43

I needed to create an algorithm which will (efficiently) take an old array and a new array and give me back the changes between the two (which items added, which removed). It ha

8条回答
  •  野性不改
    2021-02-04 06:17

    Your algorithm looks pretty good for having come up with it yourself! Congrats!
    Keep in mind thugh that while your algorithm reveals changes of the content of two arrays (item removal, etc), it does not reveal changes of content order (or removed items being added again later on).

    You could for example remove item 1 of array a and add it back in later on, technically changing array a from array b, however remaining unnoticed by your algorithm.

    array a: {1, 2, 3, 4, 5, 6}
    
    array b: {1, 2, 3, 4, 5, 6}
    
    array a: {2, 3, 4, 5, 6}    //after a.shift();
    array a: {2, 3, 4, 5, 6, 1} //after a.push(1);
    
    => a != b //your algorithm would return "a == b" though
    

    Your alorithm might be sufficient for your particular needs, however for a really strict array diff algorithm I would try to port a string diff algorithm. Basically changing the algorithm so instead of comparing chars/runs in a string it compares the items in your array.

    Javascript string diff algorithm (JS Code)

提交回复
热议问题