我有两个JavaScript数组:

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

我希望输出为:

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

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

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


当前回答

你可以试试这个:

常量union=(a,b)=>Array.from(新集合([…a,…b]));console.log(联合([“neymar”,“mesi”],[“ronaldo”,“neymmar”]);

其他回答

下面是使用Set的另一个简单解决方案:

常量o1={a:1};const arr1=['!@#$%^&*()','gh',123,o1,1,true,undefined,null];常量arr2=['!@#$%^&*()',123,'abc',o1,0x001,true,void 0,0];const mergeUnique=(…args)=>[…新集合([].contat(…arg))];console.log(mergeUnique(arr1,arr2));

最简单的方法是使用concat()合并数组,然后使用filter()删除重复项,或者使用concat()将合并的数组放入Set()中。

第一种方式:

const firstArray = [1,2, 2];
const secondArray = [3,4];
// now lets merge them
const mergedArray = firstArray.concat(secondArray); // [1,2,2,3,4]
//now use filter to remove dups
const removeDuplicates = mergedArray.filter((elem, index) =>  mergedArray.indexOf(elem) === index); // [1,2,3, 4]

第二种方式(但对UI有性能影响):

const firstArray = [1,2, 2];
const secondArray = [3,4];
// now lets merge them
const mergedArray = firstArray.concat(secondArray); // [1,2,2,3,4]
const removeDuplicates = new Set(mergedArray);

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

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]

这很快,可以整理任意数量的数组,并且可以处理数字和字符串。

function collate(a){ // Pass an array of arrays to collate into one array
    var h = { n: {}, s: {} };
    for (var i=0; i < a.length; i++) for (var j=0; j < a[i].length; j++)
        (typeof a[i][j] === "number" ? h.n[a[i][j]] = true : h.s[a[i][j]] = true);
    var b = Object.keys(h.n);
    for (var i=0; i< b.length; i++)
        b[i]=Number(b[i]);
    return b.concat(Object.keys(h.s));
}

> a = [ [1,2,3], [3,4,5], [1,5,6], ["spoon", "fork", "5"] ]
> collate( a )

[1, 2, 3, 4, 5, 6, "5", "spoon", "fork"]

如果你不需要区分5和“5”,那么

function collate(a){
    var h = {};
    for (i=0; i < a.length; i++) for (var j=0; j < a[i].length; j++)
        h[a[i][j]] = typeof a[i][j] === "number";
    for (i=0, b=Object.keys(h); i< b.length; i++)
        if (h[b[i]])
            b[i]=Number(b[i]);
    return b;
}
[1, 2, 3, 4, "5", 6, "spoon", "fork"]

可以。

如果你不介意(或者更愿意)所有值都以字符串结尾,那么就这样:

function collate(a){
    var h = {};
    for (var i=0; i < a.length; i++)
        for (var j=0; j < a[i].length; j++)
            h[a[i][j]] = true;
    return Object.keys(h)
}
["1", "2", "3", "4", "5", "6", "spoon", "fork"]

如果您实际上不需要数组,但只想收集唯一值并对其进行迭代,那么(在大多数浏览器(和node.js)中):

h = new Map();
for (i=0; i < a.length; i++)
    for (var j=0; j < a[i].length; j++)
        h.set(a[i][j]);

这可能更好。

这里有一个稍微不同的循环。通过Chrome最新版本中的一些优化,它是解决两个数组联合的最快方法(Chrome 38.0.2111)。

http://jsperf.com/merge-two-arrays-keeping-only-unique-values

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

var arr = array1.concat(array2),
  len = arr.length;

while (len--) {
  var itm = arr[len];
  if (array3.indexOf(itm) === -1) {
    array3.unshift(itm);
  }
}

while循环:约589k ops/s滤波器:~44k ops/slodash:30.8万次/秒对于循环:225k操作/秒

一条评论指出,我的一个设置变量导致我的循环领先于其他循环,因为它不需要初始化一个空数组来写入。我同意这一点,所以我已经将测试重写为公平的环境,并包含了一个更快的选项。

http://jsperf.com/merge-two-arrays-keeping-only-unique-values/52

let whileLoopAlt = function (array1, array2) {
    const array3 = array1.slice(0);
    let len1 = array1.length;
    let len2 = array2.length;
    const assoc = {};

    while (len1--) {
        assoc[array1[len1]] = null;
    }

    while (len2--) {
        let itm = array2[len2];

        if (assoc[itm] === undefined) { // Eliminate the indexOf call
            array3.push(itm);
            assoc[itm] = null;
        }
    }

    return array3;
};

在另一种解决方案中,我结合了一个答案的关联数组解决方案,以消除循环中的.indexOf()调用,该调用通过第二个循环大大降低了速度,并包含了其他用户在其答案中建议的一些其他优化。

这里的最高答案是每个值(i-1)都有一个双循环,但速度仍然很慢。lodash仍然做得很好,我仍然会向任何不介意在项目中添加库的人推荐它。对于那些不想这样做的人来说,我的while循环仍然是一个很好的答案,过滤器的答案在这里表现得很好,在我的测试中击败了最新的Canary Chrome(44.0.2360)。

如果你想加快速度,看看迈克和丹·斯托克的答案。在经历了几乎所有可行的答案之后,这些是迄今为止所有结果中最快的。