函數式編程
2021-11-25 16:45:56
我需要通過比較它們的相似度值來找出兩個數組之間的百分比。例如,我有兩個數組。const arrOne = ["one", "two", "three", "four", "five"];const arrTwo = ["one", "three", "four"];let percentage = 100 * Math.abs( (arrOne.length - arrTwo.length) / ((arrOne.length + arrTwo.length) / 2) )我需要比較這兩個數組,并需要根據相似的字符串找到它的百分比。上面的方法是,我嘗試過,但沒有得到預期的輸出
2 回答

德瑪西亞99
TA貢獻1770條經驗 獲得超3個贊
這是兩個數組之間的重疊率:
function intersectionRatio(arrOne, arrTwo){
intersection = arrOne.filter(el => arrTwo.includes(el))
elementsCount = arrOne.length + arrTwo.length - intersection.length
return intersection.length / elementsCount
}
intersectionRatio([1,2,3], [4,5,6]); // 0
intersectionRatio([1,2,3], [1,2,3]); // 1
intersectionRatio([1,2,3], [2,3,4]); // 0.5

收到一只叮咚
TA貢獻1821條經驗 獲得超5個贊
試試這個:
const arrTwoInArrOneRatio = arrTwo.filter(i=>arrOne.includes(i)).length / arrOne.length
const arrOneInArrTwoRatio = arrOne.filter(i=>arrTwo.includes(i)).length / arrTwo.length
添加回答
舉報
0/150
提交
取消