Algorithm to get changes between two arrays

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

    PHP solution for associative arrays, splitting inserts/updates/deletes into separate arrays:

    /**
     * compute differences between associative arrays.
     * the inserts, updates, deletes are returned
     * in separate arrays. Note: To combine arrays
     * safely preserving numeric keys, use $a + $b
     * instead of array_merge($a, $b).
     *
     * Author: Monte Ohrt <monte@ohrt.com>
     * Version: 1.0
     * Date: July 17th, 2014
     *
     * @param array $a1
     * @param array $a2
     * @return array ($inserts, $updates, $deletes)
     */
    get_array_differences($a1, $a2) {
        // get diffs forward and backward
        $forward = array_diff_assoc($a1, $a2);
        $backward = array_diff_assoc($a2, $a1);
        // compute arrays
        $inserts = array_diff_key($forward, $backward);
        $updates = array_intersect_key($forward, $backward);
        $deletes = array_diff_key($backward, $forward);
        return array($inserts, $updates, $deletes);
    }
    

    https://gist.github.com/mohrt/f7ea4e2bf2ec8ba7542c

    0 讨论(0)
  • 2021-02-04 06:33

    The following page has a function that removes one array from another and can be used to give you the 2 values. Remove items from a JavaScript Array with RemoveArrayItems()

    var newItemsAdded=RemoveArrayItems(oldArray,newArray);
    var ItemsRemoved =RemoveArrayItems(newArray,oldArray);
    
    0 讨论(0)
提交回复
热议问题