如何比较JavaScript中的两个数组或字符串?

时间:2019-03-14 12:37:31

标签: javascript arrays

我从复选框中选择了一个array1,我需要与最相似的数组进行比较,我该怎么做?

var array1 = ["pain", "fever", "vomit"]


var array2 = ["diarrhea", "fever", "vomit", "embolism", "bleeding"]
var array3 = ["diarrhea", "tumor", "vomit", "cold", "bleeding"]

我尝试了一些方法,但是它们只返回“ true”或“ false”,我想得到最相似的array1

2 个答案:

答案 0 :(得分:0)

您可以使用reduce计算相似元素的数量,然后按相似性对数组进行排序并获取第一个元素:

const array1 = ["pain", "fever", "vomit"];

const array2 = ["diarrhea", "fever", "vomit", "embolism", "bleeding"];
const array3 = ["diarrhea", "tumor", "vomit", "cold", "bleeding"];

const countSimilarElements = (arr1, arr2) => arr1.reduce((count, x) => count + arr2.includes(x), 0);

const orderBySimilarity = (arr1, ...arr) =>
  arr.map(x => ({ array: x, similarity: countSimilarElements(arr1, x) }))
     .sort((a, b) => b.similarity - a.similarity);

const ordered = orderBySimilarity(array1, array2, array3);
console.log(ordered);
console.log(ordered[0].array);

答案 1 :(得分:0)

此函数将要比较的数组作为“ base ”,并将其他数组的列表作为“ arr_list ”,然后返回相似性数组,显示“ arr_list ”中的每个数组与“ base ”的相似性。这样,您可以通过一次调用比较多个数组,并通过引用返回的相似度数组的 index 了解引用它们的相似度。

const a = ['11', '22', '33'], b = ['11', '44', '55', '66'], c = ['55', '33', '11', '22'], d = ['11', '66', '44', '22'];

const Similarity = (base, arr_list) => {
    let similarity = new Array(arr_list.length).fill(0);//creates similarity array which defaults to 0
    base.forEach( el => {
        arr_list.forEach( (arr, i) => similarity[i] += arr.includes(el) )
    });
    return similarity;
}
const similarity = Similarity(a, [b,c,d])
console.log(similarity)