合并两个数组,如果某个值为true,则添加属性?Javascript



我需要循环思考两个数组,并返回另一个具有不同值的数组。

两个阵列的示例:

let arr1 = ['one' , 'two' , 'three'];
let arr2 = ['four' , 'one' , 'two'];

我需要什么?

循环认为数组和返回相同的值,我希望新的数组像:

let res = [
{ name : 'one' , isSame: true },
{ name : 'two' , isSame: true },
{ name : 'three' },
{ name : 'four' }
];

我删除了重复项,并将重复值的isSame值添加为true。

一个和两个重复(两次)。

我尝试过的

let arr3 = arr1.map((item, i) =>
Object.assign({}, item, arr2[i])
); 

但我得到了一个分裂的阵列,它删除了重复的

减少到一个中间对象,然后映射该对象的条目:

const arr1 = ['one' , 'two' , 'three'];
const arr2 = ['four' , 'one' , 'two'];
const result = Object.entries([...arr1, ...arr2].reduce(
(a, v) => ({ ...a, [v]: v in a }),
{}
)).map(([name, isSame]) => ({ name, isSame }));
console.log(result);

reduce()回调中的扩展行为增加了时间复杂性,有利于更简洁,但可以很容易地避免,使该解决方案O(n):

const arr1 = ['one' , 'two' , 'three'];
const arr2 = ['four' , 'one' , 'two'];
const result = Object.entries([...arr1, ...arr2].reduce(
(a, v) => {
a[v] = v in a;
return a;
},
{}
)).map(([name, isSame]) => ({ name, isSame }));
console.log(result);

我建议您使用reduce()进行

let arr1 = ['one' , 'two' , 'three'];
let arr2 = ['four' , 'one' , 'two'];
let arr3 = arr1.concat(arr2)
let result = arr3.reduce((a,c) =>{
let obj = a.find(i => i.name == c)
if(obj){
obj['isSame'] = true
}else{
a.push({'name':c})
}
return a
},[])
console.log(result)


更新:不含reduce()的解决方案,使用set()去除重复元素,并使用includes()查找重复元素

let arr1 = ['one' , 'two' , 'three'];
let arr2 = ['four' , 'one' , 'two'];
let arr3 = [...new Set(arr1.concat(arr2))]
let result = arr3.map(a =>{
let data = {'name':a}
if(arr1.includes(a) && arr2.includes(a)){
data["isSame"] = true
}
return data
})
console.log(result)

更新:根据OP的评论,显示相反的结果

let arr1 = ['one' , 'two' , 'three'];
let arr2 = ['four' , 'one' , 'two'];
let arr3 = [...new Set(arr1.concat(arr2))]
let result = arr3.map(a =>{
let data = {'name':a}
if(!arr1.includes(a) || !arr2.includes(a)){
data["isSame"] = true
}
return data
})
console.log(result)

由于您不想要reduce,因此可以循环遍历每个项,并检查接下来的几个值。

这在本质上更快,函数调用更少,只有两个用于循环。

let arr1 = ['one', 'two', 'three'];
let arr2 = ['four', 'one', 'two'];
console.log(merge(arr1, arr2));
function merge(a, b) {
const merged = a.concat(b); // combine arrays
const result = [];

let stop = merged.length; // create a variable for when to stop
for(let i = 0; i < stop; i++) {
const current = merged[i];
let same = false;

// look through the rest of the array for indexes
for(let t = i + 1; t < stop; t++) {
if(current === merged[t]) {
same = true;
merged.splice(t, 1); // remove duplicate elements from the array so we don't come across it again
stop--; // we've removed an element from the array, so we have to stop 1 earlier
// we don't break this loop because there may be more than 2 occurences
}
}
const out = { name: current };
if(same) out.isSame = true;

result.push(out);
}
return result;
}

  • 我使用了数组的map()函数
  • map()通过对每个有效条目执行代码逻辑来返回新的数组
  • [...new Set([...arr1, ...arr2])],这将返回具有唯一值的新数组
  • 我假设,您正在检查值是否在两个数组中,并基于此返回对象

let arr1 = ['one', 'two', 'three'];
let arr2 = ['four', 'one', 'two'];
let mergedArray = [...new Set([...arr1, ...arr2])];
let result = mergedArray.map(value => {
if (arr1.includes(value) && arr2.includes(value)) {
return {
value,
isInBothArray: true
}
} else {
return {
value,
isInBothArray: false
}
}
});
console.log(result);

const arr1 = ['one' , 'two' , 'three'];
const arr2 = ['four' , 'one' , 'two'];
// returns the duplicate values in the two arrays
const findDuplicates = (arr) => {
let sorted_arr = arr.slice().sort();
let results = [];
for (let i = 0; i < sorted_arr.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
return results;
}
let values = ([...new Set([...arr1, ...arr2])]);
let duplicates = findDuplicates(values);
let retval = [];
for(let i = 0; i < values.length; i++) {
let isSame = duplicates.includes(values[i]);
retval.push({name: values[i], isSame: isSame})
}

const arr1 = ['one', 'two', 'three'];
const arr2 = ['four', 'one', 'two'];
const result = Array.from(new Set(arr1.concat(arr2))).reduce((p, c) => {
const obj = { name: c };
if (arr1.concat(arr2).join("").split(c).length - 1 > 1) obj.isSame = true;
p.push(obj)
return p;
}, []);
console.log(result);

最新更新