我有两个JavaScript数组:

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

我希望输出为:

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

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

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


当前回答

模块化,通用

这可以通过组成两个基本功能来实现。

const getUniqueMerge = (...arrs) => getUniqueArr(mergeArrs(...arrs))
const getUniqueArr = (array) => Array.from(new Set(array))  
const mergeArrs = (...arrs) => [].concat(...arrs)

它可以处理无限的数组或值

console.log(getUniqueMerge(["Vijendra","Singh"],["Singh", "Shakya"])
// ["Vijendra", "Singh", "Shakya"]

console.log(getUniqueMerge(["Sheldon", "Cooper"], ["and", "Cooper", "Amy", "and"], "Farrah", "Amy", "Fowler"))
// ["Sheldon", "Cooper", "and", "Amy", "Farrah", "Fowler"]

其他回答

取两个数组a和b

var a = ['a','b','c'];

var b = ['d','e','f'];
var c = a.concat(b); 


//c is now an an array with: ['a','b','c','d','e','f']

如果您合并对象数组,请考虑使用lodash UnionBy函数,它允许您设置自定义谓词比较对象:

import { unionBy } from 'lodash';

const a = [{a: 1, b: 2}];
const b = [{a: 1, b: 3}];
const c = [{a: 2, b: 4}];

const result = UnionBy(a,b,c, x => x.a);

结果是:〔{a:1;b:2},{a:2;b:4}〕

结果中使用了来自数组的第一个传递匹配

这是一个使用扩展运算符和数组泛型的ECMAScript 6解决方案。

目前,它只适用于Firefox,也可能适用于Internet Explorer技术预览版。

但如果你使用巴别尔,你现在就可以拥有它。

常量输入=[[1, 2, 3],[101, 2, 1, 10],[2, 1]];常量合并重复数据消除=(arr)=>{return[…new Set([].contat(…arr))];}console.log(“输出”,合并重复数据消除(输入));

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

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]

这很简单,可以用jQuery在一行中完成:

var arr1 = ['Vijendra', 'Singh'], arr2 =['Singh', 'Shakya'];

$.unique(arr1.concat(arr2))//one line

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