JSFiddle - React, Tailwind, and code Playground

by uedatakuya

JavaScript

//var array1 = [1, 2,2, 1,5, 'a', 'b'];
//var array2 = [1, 2, 2, 2, 3, 'a', 'b', 'c'];

var array1 = [1, 2, 3, 4, 5];
var array2 = [1, 1, 2, 3, 3, 5];

function arrayDiff(a, b) {
    var commons = [];
    var addeds = [];
    var deleteds = [];

    var i = 0;
    a.forEach(function(o, j) {
        var idx = b.indexOf(o, i);
        if (idx >= 0) {
            commons.push({
                index: j,
                value: o
            });
            i = idx + 1;
        } else {
            deleteds.push({
                index: j,
                value: o
            });
        }
    });

    i = 0;
    b.forEach(function(o, j) {
        var idx = a.indexOf(o, i);
        if (idx >= 0) {
            i = idx + 1;
        } else {
            addeds.push({
                index: i,
                value: o
            });
        }
    });

    return {
        commons: commons,
        addeds: addeds,
        deleteds: deleteds
    };
}

function comparator(a, b) {
    return a.index - b.index;
}

function patch(array, diff) {
    var patched = [].concat(array);

    diff.deleteds.sort(comparator);
    diff.addeds.sort(comparator);

    diff.deleteds.forEach(function(del, i) {
        patched.splice(del.index - i, 1);
        diff.addeds.forEach(function(add) {
            if (add.index > del.index) {
                add.index -= 1;
            }
        });
    });
    console.log(patched);

    diff.addeds.forEach(function(add, i) {
        patched.splice(add.index + i, 0, add.value);
    });

    return patched;
}

var diff = arrayDiff(array1, array2);
console.log(diff);
var patched = patch(array1, diff);
console.log(patched);