我有两个JavaScript数组:

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];

我希望输出为:

var array3 = ["Vijendra","Singh","Shakya"];

输出数组应删除重复的单词。

如何在JavaScript中合并两个数组,以便从每个数组中只获得唯一的项目,其顺序与它们插入原始数组的顺序相同?


当前回答

给定两个没有重复的简单类型的排序数组,这将在O(n)时间内合并它们,并且输出也将被排序。

function merge(a, b) {
    let i=0;
    let j=0;
    let c = [];
    for (;;) {
        if (i == a.length) {
            if (j == b.length) return c;
            c.push(b[j++]);
        } else if (j == b.length || a[i] < b[j]) {
            c.push(a[i++]);
        } else {
            if (a[i] == b[j]) ++i;   // skip duplicates
            c.push(b[j++]);
        }
    }
}

其他回答

构建一个测试人员来检查一些面向性能的答案的速度。请随意添加更多内容。到目前为止,Set是最简单和最快的选项(随着记录数量的增加,它的边距会更大),至少对于简单的number类型来说是如此。

常量记录=10000,//每个阵列的最大记录数max_int=100,//每个数组的最大整数值dup_rate=.5//复制率让perf={},//性能记录器,ts=0,te=0,array1=[],//初始化数组array2=[],array1b=[],array2b=[],a=[];//填充随机化数组for(设i=0;i<记录;i++){设r=Math.random(),n=r*max_int;如果(Math.random()<.5){array1.push(n);r<dup_rate&&array2.push(n);}其他{阵列2.push(n);r<dup_rate&&array1.push(n);}}//缺少rfdc的简单深度副本,以防有人想要使用更复杂的数据类型进行测试array1b=JSON.parse(JSON.stringify(array1));array2b=JSON.parse(JSON.stringfy(array2));console.log('数组1中的记录:',array1.length,array1b.length);console.log('数组2中的记录:',array2.length,array2b.length);//试验方法1(jsperf per@Pitouli)ts=performance.now();for(设i=0;i<array2.length;i++)如果(array1.indexOf(array2[i])==-1)array1.push(array2[i])//修改数组1te=performance.now();perf.m1=te-ts;console.log('方法1合并',array1.length,'记录在:',perf.m1);array1=JSON.parse(JSON.stringify(array1b))//重置阵列1//测试方法2(经典的Each)ts=performance.now();array2.forEach(v=>array1.includes(v)?null:array1.push(v))//修改数组1te=performance.now();perf.m2=te-ts;console.log('方法2合并',array1.length,'记录在:',perf.m2中);//测试方法3(最简单的本机选项)ts=performance.now();a=[…新集合([…array1,…array2])]//不修改源阵列te=performance.now();perf.m3=te-ts;console.log('方法3合并',a.length,'记录在:',perf.m3);//测试方法4(选定答案)ts=performance.now();a=阵列1.concat(阵列2)//不修改源阵列for(设i=0;i<a.length;++i){for(设j=i+1;j<a.length;++j){如果(a[i]===a[j])a.接头(j-,1);}}te=performance.now();perf.m4=te-ts;console.log('Method 4 merged',a.length,'records in:',perf.m4);//试验方法5(@Kamil Kielczewski)ts=performance.now();函数K(arr1,arr2){设r=[],h={};而(arr1.length){设e=arr1.shift()//修改数组1如果(!h[e])h[e]=1&&r.push(e);}而(arr2.长度){设e=arr2.shift()//修改数组2如果(!h[e])h[e]=1&&r.push(e);}返回r;}a=K(阵列1,阵列2);te=performance.now();perf.m5=te-ts;console.log('Method 5 merged',a.length,'records in:',perf.m4);array1=JSON.parse(JSON.stringify(array1b))//重置阵列1array2=JSON.parse(JSON.stringfy(array2b))//重置阵列2for(设i=1;i<6;i++){console.log('方法:',i,'速度为',(perf[m'+i]/perf.m1*100).toFixed(2),'方法1的%');}

下面是一个简单的例子:

var unique = function(array) {
    var unique = []
    for (var i = 0; i < array.length; i += 1) {
        if (unique.indexOf(array[i]) == -1) {
            unique.push(array[i])
        }
    }
    return unique
}

var uniqueList = unique(["AAPL", "MSFT"].concat(["MSFT", "BBEP", "GE"]));

我们定义unique(array)来删除冗余元素,并使用concat函数来组合两个数组。

最好也是最简单的方法是使用JavaScript的函数“some()”,该函数返回true或false,指示数组是否包含对象的元素。您可以这样做:

var array1 = ["Vijendra","Singh"]; 
var array2 = ["Singh", "Shakya"];

var array3 = array1;

array2.forEach(function(elementArray2){
    var isEquals = array1.some(function(elementArray1){
        return elementArray1 === elementArray2;
    })
    if(!isEquals){
        array3.push(elementArray2);
    }
});
console.log(array3);

结果:

["Vijendra", "Singh", "Shakya"]

如你所愿。。。无需复制。。。

新解决方案(使用Array.prototype.indexOf和Array.prototype.cocat):

Array.prototype.uniqueMerge = function( a ) {
    for ( var nonDuplicates = [], i = 0, l = a.length; i<l; ++i ) {
        if ( this.indexOf( a[i] ) === -1 ) {
            nonDuplicates.push( a[i] );
        }
    }
    return this.concat( nonDuplicates )
};

用法:

>>> ['Vijendra', 'Singh'].uniqueMerge(['Singh', 'Shakya'])
["Vijendra", "Singh", "Shakya"]

Array.prototype.indexOf(用于internet explorer):

Array.prototype.indexOf = Array.prototype.indexOf || function(elt)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0) ? Math.ceil(from): Math.floor(from); 
    if (from < 0)from += len;

    for (; from < len; from++)
    {
      if (from in this && this[from] === elt)return from;
    }
    return -1;
  };

合并无限数量的数组或非数组并保持其唯一性:

function flatMerge() {
    return Array.prototype.reduce.call(arguments, function (result, current) {
        if (!(current instanceof Array)) {
            if (result.indexOf(current) === -1) {
                result.push(current);
            }
        } else {
            current.forEach(function (value) {
                console.log(value);
                if (result.indexOf(value) === -1) {
                    result.push(value);
                }
            });
        }
        return result;
    }, []);
}

flatMerge([1,2,3], 4, 4, [3, 2, 1, 5], [7, 6, 8, 9], 5, [4], 2, [3, 2, 5]);
// [1, 2, 3, 4, 5, 7, 6, 8, 9]

flatMerge([1,2,3], [3, 2, 1, 5], [7, 6, 8, 9]);
// [1, 2, 3, 5, 7, 6, 8, 9]

flatMerge(1, 3, 5, 7);
// [1, 3, 5, 7]