如何在javascript中找到两个数组的联合而不使用任何内置的js方法?



给定大小为n和m的数组a和b,其中m>=n。任务是查找这两个数组之间的并集并返回该并集数组。

let a = [5, 3];
let b = [1, 2, 3, 4, 5];
let a = [2, 2];
let b = [1, 1];
let n = a.length;
let m = b.length;
for (let i = 0; i < m; i++) {
let present = true;

for (let j = 0; j < n; j++) {
if (b[i] === a[j]) {
present = false;
}
}

if (present !== false) {
a.push(b[i]);
}
}

我正试图解决这个问题,从过去的2小时,但我没有得到所需的输出,所以请帮助我解决这个问题。

实现此目的的一种方法是利用Javascript中字典的使用。字典是Javascript中的对象,它们用于存储键值对。键是唯一的,所以如果您添加一个已经存在的键,它将覆盖之前的值。这对于查找两个数组的并集很有用,因为您可以将第一个数组的所有元素添加到字典中,然后将第二个数组的所有元素添加到字典中。字典将只包含唯一的元素,因此两个数组的并集将是字典的键。

// Javascript code to find the union of two arrays
function array_union(arr1, arr2) {
// Create a new dictionary
var union = {};
// Loop through the first array
for (var i = 0; i < arr1.length; i++) {
// Add the element to the dictionary
union[arr1[i]] = true;
}
// Loop through the second array
for (var i = 0; i < arr2.length; i++) {
// Add the element to the dictionary
union[arr2[i]] = true;
}
// Return the dictionary keys
return Object.keys(union);
}

如果你不想使用字典,你可以使用这个简单的方法:

function array_union(arr1, arr2) {
// Create a new array
var union = [];
// Loop through the first array
for (var i = 0; i < arr1.length; i++) {
// Check if the element is in the union array
if (union.indexOf(arr1[i]) == -1) {
// Add the element to the union array
union.push(arr1[i]);
}
}
// Loop through the second array
for (var i = 0; i < arr2.length; i++) {
// Check if the element is in the union array
if (union.indexOf(arr2[i]) == -1) {
// Add the element to the union array
union.push(arr2[i]);
}
}
// Return the union array
return union;
}

最后是"酷孩子"这样做的方法是使用reduce函数。这是一个非常强大的函数,可用于对数组执行缩减(查看此解释)。在本例中,我们使用它来创建一个新数组,其中只添加数组中不存在的项。

function array_union(n, m) {
// Do a reduction on the two arrays to create a new array where items are only added if they are not already in the array
let union = n.concat(m).reduce((a, b) => {
if (a.indexOf(b) == -1) {
a.push(b);
}
return a;
}, []);

return union;
}

我认为这不是最好的解决方案,但它是一个开始:

const union=(m,n)=>{
let obj1={}
let obj2={}
let arr=[]
for(let i=0;i<m.length;i++){
obj1[m[i]]=obj1[m[i]]?obj1[m[i]]++:1
obj2[n[i]]=obj2[n[i]]?obj2[n[i]]++:1
}
for(let [key,value] of Object.entries(
Object.keys(obj1).length>Object.keys(obj2).length?obj1:obj2
)){
if(obj1[key] && obj2[key]){
arr.push(parseInt(key))
}
}
return arr
}
let a = [1,2,2,3];
let b = [1,2,3,4,5];

console.log(union(a,b))

相关内容