我有两个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中合并两个数组,以便从每个数组中只获得唯一的项目,其顺序与它们插入原始数组的顺序相同?
当前回答
可以使用Set完成。
var array1=[“Vijendra”,“Singh”];var array2=[“Singh”,“Shakya”];var array3=array1.concat(array2);var tempSet=新集合(array3);array3=Array.from(tempSet);//显示输出document.body.querySelector(“div”).innerHTML=JSON.stringify(array3);<div style=“width:100%;height:4rem;line height:4rem;background color:steelblue;color:#DDD;text align:center;font-family:Calibri”>临时文本</div>
其他回答
只需避开嵌套循环(O(n^2))和.indexOf()(+O(n))。
函数合并(a,b){var哈希={};变量i;对于(i=0;i<a.length;i++){hash[a[i]=真;}对于(i=0;i<b.length;i++){hash[b[i]]=真;}return Object.keys(哈希);}var array1=[“Vijendra”,“Singh”];var array2=[“Singh”,“Shakya”];var array3=合并(array1,array2);console.log(array3);
const merge(…args)=>(新集合([].contat(…arg)))
对于大型输入,更好的选择是对数组进行排序。然后合并它们。
function sortFunction(a, b) {
return a - b;
}
arr1.sort(sortFunction);
arr2.sort(sortFunction);
function mergeDedup(arr1, arr2) {
var i = 0, j = 0, result = [];
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
writeIfNotSameAsBefore(result, arr1[i]);
i++;
}
else if (arr1[i] > arr2[j]) {
writeIfNotSameAsBefore(result, arr2[j]);
j++;
}
else {
writeIfNotSameAsBefore(result, arr1[i]);
i++;
j++;
}
}
while (i < arr1.length) {
writeIfNotSameAsBefore(result, arr1[i]);
i++;
}
while (j < arr2.length) {
writeIfNotSameAsBefore(result, arr2[j]);
j++;
}
return result;
}
function writeIfNotSameAsBefore(arr, item) {
if (arr[arr.length - 1] !== item) {
arr[arr.length] = item;
}
return arr.length;
}
排序将采用O(nlogn+mlogm),其中n和m是数组的长度,O(x)用于合并,其中x=Max(n,m);
这是我的解决方案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"]
]
Array.prototype.add = function(b){
var a = this.concat(); // clone current object
if(!b.push || !b.length) return a; // if b is not an array, or empty, then return a unchanged
if(!a.length) return b.concat(); // if original is empty, return b
// go through all the elements of b
for(var i = 0; i < b.length; i++){
// if b's value is not in a, then add it
if(a.indexOf(b[i]) == -1) a.push(b[i]);
}
return a;
}
// Example:
console.log([1,2,3].add([3, 4, 5])); // will output [1, 2, 3, 4, 5]