let arr1 = [{ type: "t1", chr: "多躲大定夺" }];
let arr2 = [
{ type: "t2", chr: "多躲大打弟" },
{ type: "d2", chr: "定夺洞" },
];
let arr3 = [
{source: "t1", target: "t2", value: 3},
{source: "t1", target: "d2", value: 2}
]
想从arr1和arr2实现arr3。
根据chr属性值:
当arr1的 chr值与arr2[0]中chr相同时,为source赋值't1", target赋值"t2", 并根据相同的数量赋值value;
当arr1的 chr值与arr2[1]中chr相同时,为source赋值't1", target赋值"d2",并根据相同的数量赋值value;
let arr1 = [{type: "t1", chr: "多躲大定夺"}];
let arr2 = [
{type: "t2", chr: "多躲大打弟"},
{type: "d2", chr: "定夺洞"},
];
let arr3 = [
{source: "t1", target: "t2", value: 3},
{source: "t1", target: "d2", value: 2}
]
/**
* 计算相似度的函数需要你来实现了,目前的悬赏额度我写不出完美的,所以写死了
* @param str1
* @param str2
* @returns {number}
*/
function test(str1, str2) {
let char1 = str1.split('');
let char2 = str2.split('');
let count = 0;
for (let i = 0; i < char1.length; i++) {
for (let j = 0; j < char2.length; j++) {
if (char1[i] == char2[j]) {
count++
}
}
}
return count;
}
let result = arr2.map(item => {
let filter = arr1.map(subItem => ({
...subItem,
value: test(subItem.chr, item.chr)
})).filter(subItem => subItem.value > 0);
filter = filter[0] || {value: 0}
return ({
source: filter.type,
target: item.type,
value: filter.value
})
}).filter(item => item.value > 0);
console.log(result)
let arr1 = [
{ type: "t1", chr: "多躲大定夺" },
{ type: "t1", chr: "定夺洞" }
];
let arr2 = [
{ type: "t2", chr: "多躲大定夺" },
{ type: "t2", chr: "多躲大定夺" },
{ type: "d2", chr: "定夺洞" },
];
let arr3 = [];
arr1.forEach((i) => {
arr2.forEach((v) => {
if (i.chr === v.chr) {
let existObj= arr3.find((item) => {
return item.target === v.type;
});
if (existObj) {
existObj.value += 1;
} else {
arr3.push({ source: i.type, target: v.type, value: 1 });
}
}
});
});
console.log(arr3);
//将数组1和2合并
arr3 = arr1 .concat(arr2 )
//根据chr去重数组3
unique(arr3) {
const res = new Map()
return arr3.filter((item) => !res.has(item.chr) && res.set(item.chr, 1))
}
不知道是这个意思么?
let arr1 = [{ type: "t1", chr: "多躲大打弟" },{ type: "t1", chr: "定夺洞" }];
let arr2 = [
{ type: "t2", chr: "多躲大打弟" },
{ type: "t3", chr: "多躲大打弟" },
{ type: "d2", chr: "定夺洞" },
];
let arr3=[]
for(var o in arr1){
var array = [];
for(var i in arr2){
if(arr1[o].chr==arr2[i].chr){
if(array[arr1[o].chr] !== undefined){
array[arr1[o].chr].value=array[arr1[o].chr].value+1;
}
else{
array[arr1[o].chr] = {source: arr1[o].type, target: arr2[i].type, value: 1};
}
//
}
}
for(key in array){
arr3.push(array[key]);
}
}
console.log(arr3);
看看有没有帮助
https://b23.tv/mq7xAQp