How to merge two arrays in JavaScript and de-dupli

2018-12-30 23:45发布

I have two JavaScript arrays:

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

I want the output to be:

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

The output array should have repeated words removed.

How do I merge two arrays in JavaScript so that I get only the unique items from each array in the same order they were inserted into the original arrays?

30条回答
爱死公子算了
2楼-- · 2018-12-31 00:41

This is an ECMAScript 6 solution using spread operator and array generics.

Currently it only works with Firefox, and possibly Internet Explorer Technical Preview.

But if you use Babel, you can have it now.

// Input: [ [1, 2, 3], [101, 2, 1, 10], [2, 1] ]
// Output: [1, 2, 3, 101, 10]
function mergeDedupe(arr)
{
  return [...new Set([].concat(...arr))];
}
查看更多
荒废的爱情
3楼-- · 2018-12-31 00:41
var arr1 = [1, 3, 5, 6];
var arr2 = [3, 6, 10, 11, 12];
arr1.concat(arr2.filter(ele => !arr1.includes(ele)));
console.log(arr1);

output :- [1, 3, 5, 6, 10, 11, 12]
查看更多
路过你的时光
4楼-- · 2018-12-31 00:42
Array.prototype.merge = function(/* variable number of arrays */){
    for(var i = 0; i < arguments.length; i++){
        var array = arguments[i];
        for(var j = 0; j < array.length; j++){
            if(this.indexOf(array[j]) === -1) {
                this.push(array[j]);
            }
        }
    }
    return this;
};

A much better array merge function.

查看更多
余欢
5楼-- · 2018-12-31 00:43

You can achieve it simply using Underscore.js's => uniq:

array3 = _.uniq(array1.concat(array2))

console.log(array3)

It will print ["Vijendra", "Singh", "Shakya"].

查看更多
流年柔荑漫光年
6楼-- · 2018-12-31 00:44

for the sake of it... here is a single line solution:

const x = [...new Set([['C', 'B'],['B', 'A']].reduce( (a, e) => a.concat(e), []))].sort()
// ['A', 'B', 'C']

Not particularly readable but it may help someone:

  1. Applies a reduce function with the initial accumulator value set to an empty array.
  2. The reduce function uses concat to append each sub-array onto the accumulator array.
  3. The result of this is passed as a constructor parameter to create a new Set.
  4. The spread operator is used to convert the Set to an array.
  5. The sort() function is applied to the new array.
查看更多
高级女魔头
7楼-- · 2018-12-31 00:45

Just steer clear of nested loops (O(n^2)), and .indexOf() (+O(n)).

function merge(a, b) {
    var hash = {}, i;
    for (i=0; i<a.length; i++) {
        hash[a[i]]=true;
    } 
    for (i=0; i<b.length; i++) {
        hash[b[i]]=true;
    } 
    return Object.keys(hash);
}
查看更多
登录 后发表回答