UNPKG

jaccard-array

Version:

Very simple package for measuring the similarity of two sets by their shared members.

36 lines (30 loc) 1.01 kB
module.exports = function(arrayA, arrayB){ if (Array.isArray(arrayA) && Array.isArray(arrayB)) { // create sets from arrays to ensure unique values let setA = new Set(arrayA); let setB = new Set(arrayB); let intersection = countIntersection(setA, setB); let union = countUnion(setA, setB); return getJaccardIndex(intersection, union); } else { throw 'Parameter(s) should be of type Array.'; } } function countIntersection(setA, setB) { let refArray = [...setA]; // iterate over setA as an array // return 1/0 for every element in/not in setB // return the sum return refArray .map(elem => setB.has(elem) ? 1 : 0) .reduce((culminative, current) => culminative+current ); } function countUnion(setA, setB){ //create a new set of unique elements from A and B let union = new Set([...setA, ...setB]); // return its size return union.size; } function getJaccardIndex(intersection, union) { return intersection / union; }