我有两个JavaScript数组:
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
我希望输出为:
var array3 = ["Vijendra","Singh","Shakya"];
输出数组应删除重复的单词。
如何在JavaScript中合并两个数组,以便从每个数组中只获得唯一的项目,其顺序与它们插入原始数组的顺序相同?
我有两个JavaScript数组:
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
我希望输出为:
var array3 = ["Vijendra","Singh","Shakya"];
输出数组应删除重复的单词。
如何在JavaScript中合并两个数组,以便从每个数组中只获得唯一的项目,其顺序与它们插入原始数组的顺序相同?
当前回答
//1.merge two array into one array
var arr1 = [0, 1, 2, 4];
var arr2 = [4, 5, 6];
//for merge array we use "Array.concat"
let combineArray = arr1.concat(arr2); //output
alert(combineArray); //now out put is 0,1,2,4,4,5,6 but 4 reapeat
//2.same thing with "Spread Syntex"
let spreadArray = [...arr1, ...arr2];
alert(spreadArray); //now out put is 0,1,2,4,4,5,6 but 4 reapete
/*
if we need remove duplicate element method use are
1.Using set
2.using .filter
3.using .reduce
*/
其他回答
/***对仅保留唯一值的数组进行重复数据消除。*使用哈希表(js对象)过滤重复项。*保持数组元素的顺序。*该算法对于大型阵列(线性时间)特别有效。*/函数数组UniqueFast(arr){var seen={};var结果=[];变量i,长度=arr.length;对于(i=0;i<len;i++){var项目=arr[i];//哈希表查找if(!seed[item]){result.push(项);seed[项目]=真;}}返回结果;}/////测试var array1=[“Vijendra”,“Singh”];var array2=[“Singh”,“Shakya”];var result=arrayUniqueFast(array1.concat(array2));document.write('<br>result:'+result);
有关阵列重复数据消除的其他方法,请参阅我的基准测试:https://jsperf.com/de-duplicate-an-array-keeping-only-unique-values
这是我的解决方案https://gist.github.com/4692150深度相等且易于使用的结果:
function merge_arrays(arr1,arr2)
{
...
return {first:firstPart,common:commonString,second:secondPart,full:finalString};
}
console.log(merge_arrays(
[
[1,"10:55"] ,
[2,"10:55"] ,
[3,"10:55"]
],[
[3,"10:55"] ,
[4,"10:55"] ,
[5,"10:55"]
]).second);
result:
[
[4,"10:55"] ,
[5,"10:55"]
]
最好也是最简单的方法是使用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"]
如你所愿。。。无需复制。。。
function set(a, b) {
return a.concat(b).filter(function(x,i,c) { return c.indexOf(x) == i; });
}
如果要检查唯一对象,请在比较中使用JSON.stringify。
function arrayUnique(array) {
var a = array.concat();
for(var i=0; i<a.length; ++i) {
for(var j=i+1; j<a.length; ++j) {
if(JSON.stringify(a[i]) === JSON.stringify(a[j]))
a.splice(j--, 1);
}
}
return a;
}