我有一个数组:
const myArray1 = [{tags: ['tag-1', 'tag-2']}, {tags: ['tag-1']}, {tags: ['tag-5', 'tag-8']}]
还有一个array2:
const myArray2 = [
{
tags: [
"tag-122",
"tag-1",
"tag-2",
"tag-12"
]
},
{
tags: [
"tag-1",
"tag-10",
"tag-12"
]
},
{
tags: [
"tag-5"
]
}
];
我想要一个数组
const resultArray = [{tags: ['tag-1', 'tag-2'], count: 2}, {tags: ['tag-1'], count: 2}, {tags: ['tag-5', 'tag-8'], count: 1}]
对于myArray1中的每个元素,请检查myArray1中是否包含数组标签中的任何元素。如果包含,找到出现次数
我尝试制作一个myArray2标签数组,然后为myArray1的每个元素找到数组中的出现
const result = myArray2.reduce((acc, el) => {
el.tags && el.tags.map(tag => acc.push(tag));
return acc;
}, []);
答案 0 :(得分:2)
我将myArray2
转换为Set数组以降低计算复杂性,然后.map
array2
并检查是否有.some
被迭代的标签在集合中,用reduce
计算出现的次数:
const myArray1=[{tags:["tag-1","tag-2"]},{tags:["tag-1"]},{tags:["tag-5","tag-8"]}],
myArray2=[{tags:["tag-122","tag-1","tag-2","tag-12"]},{tags:["tag-1","tag-10","tag-12"]},{tags:["tag-5"]}];
const arr2Sets = myArray2.map(({ tags }) => new Set(tags));
const resultArray = myArray1.map(({ tags }) => {
const count = arr2Sets.reduce(
(a, set) => a + tags.some(tag => set.has(tag)),
0
);
return { tags, count };
});
console.log(resultArray);