What is the fastest way to merge an array in JavaScript, where comparisons are expensive?

I want to combine two arrays in JavaScript. Unfortunately, comparing the specific data that I use is expensive. What is the best algorithm for combining my lists with the least number of comparisons?

EDIT: I have to note that the two arrays are sorted, and I would like the merged content to be sorted and only have unique values.

EDIT: upon request I will give you my current code, but that really doesn't help.

// Merges arr1 and arr2 (placing the result in arr1)
merge = function(arr1,arr2) {
    if(!arr1.length) {
        Array.prototype.push.apply(arr1,arr2);
        return;
    }
    var j, lj;
    for(var s, i=0, j=0, li=arr1.length, lj=arr2.length; i<li && j<lj;) {
        s = compare(arr1[i], arr2[j]);
        if(s<0) ++i;
        else if(s==0) ++i, ++j;
        else arr1.splice(i,0, arr2[j++]);
    }
    if(j<lj) Array.prototype.push.apply(arr1, arr2.slice(j));
};
+3
source share
3 answers

, merge sort , . :

function merge(left,right)
    var list result
    while length(left) > 0 and length(right) > 0
        if first(left) ≤ first(right)
            append first(left) to result
            left = rest(left)
        else
            append first(right) to result
            right = rest(right)
    end while
    if length(left) > 0 
        append left to result
    else  
        append right to result
    return result
+1

, :

Array.prototype.unique = function () {
    var r = new Array();
    o:for(var i = 0, n = this.length; i < n; i++)
    {
        for(var x = 0, y = r.length; x < y; x++)
        {
            if(r[x]==this[i])
            {
                continue o;
            }
        }
        r[r.length] = this[i];
    }
    return r;
}

, :

var MainArray= arr1.concat(arr2);

, :

var MainArray= MainArray.unique();

:

var MainArray= MainArray.sort(); //Or you own sort if you have one

, , , .

+1

, . , , . . - . D3 .

function merge(right,left) {
    var map_right = {},
        map_left = {};
    right.forEach(function(n) {
        map_right[n.name] = n;
    });
    left.forEach(function(n) {
        map_left[n.name] = n;
    });
    for(var n in map_left) {
        if (map_right[n] === undefined) {
            left.splice(nodes.indexOf(map_b[n]),1);
        }
    }
    right.forEach(function (n) {
        if (map_left[n.name] === undefined) {
            left.push(n);
        }
    });
}
0

Source: https://habr.com/ru/post/1757090/


All Articles