React.js中两个数字之间的百分比

时间:2019-10-18 14:42:06

标签: javascript

我需要通过比较相似度值来找出两个数组之间的百分比。例如,我有两个数组。

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 个答案:

答案 0 :(得分:0)

尝试这个:

const arrTwoInArrOneRatio = arrTwo.filter(i=>arrOne.includes(i)).length / arrOne.length
const arrOneInArrTwoRatio = arrOne.filter(i=>arrTwo.includes(i)).length / arrTwo.length

答案 1 :(得分:0)

这是两个数组之间的重叠率:

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