Algorithm to get changes between two arrays

后端 未结 8 1377
难免孤独
难免孤独 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:27

    I think the implementation of the diff method is correct, the time complexity of your algorithm is O(n * log(n)) because of the sort methods. If you use arrays, you need to sort them before the comparison and the time complexity of sorting algorithms is at least O(n * log(n)).

    If the o and n arrays cannot contain the same value more than once, maybe the use of objects (associative arrays) instead of arrays is a better choice.

    Example:

    function diff(o, n) { 
        var a = {}; var r = {}; 
    
        for (var i in o) {
            if (!(i in n)) {
                r[i] = 1;
            }
        }
        for (var i in n) {
            if (!(i in o)) {
                a[i] = 1;
            }
        }
        return {added: a, removed: r};
    }
    
        // how to use
    var o = {"a":1, "b":1, "ab":1};
    var n = {"a":1, "aa":1};
    
    var diffon = diff (o, n);
    
        // display the results
    var added = "", removed = "";
    for (var i in diffon.added) {
        added += i + ", ";
    }
    for (var i in diffon.removed) {
        removed += i + ", ";
    }
    
    alert ("added: " + added);
    alert ("removed: " + removed);
    

    The time complexity in that case is O(n).

    If you need further details about arrays, associative arrays in JavaScript, I suggest you the following link: Array object

提交回复
热议问题