简体   繁体   中英

JavaScript - compare multiple arrays to one

I would like to output which of 'buns' and 'duns' has the most elements in common with 'me'. How should I do this?

var buns = ['bap', 'bun', 'bop'];
var duns = ['dap', 'dun', 'dop'];

var me = ['dap', 'bun', 'bop'];

reduce over the array to be tested and check if each element is in me .

function common(arr1, arr2) {
  return arr2.reduce(function (p, c) {
    if (arr1.indexOf(c) > -1) p++;
    return p;
  }, 0);
}

common(me, buns); // 2
common(me, duns); // 1

DEMO

Index important

function hamd(a, b) {
    return a.reduce((sum, item, i) => {
        if (item !== b[i]) return sum + 1;
        return sum;
    }, 0);
}

Index not important, duplicates not important

function diff(a, b) {
    return a.reduce((sum, item, i) => {
        if (b.indexOf(item) === -1) return sum + 1;
        return sum;
    }, 0);
}

Index not important, duplicates important

function diffU(a, b) {
    b = b.slice();
    return a.reduce((sum, item, i) => {
        let i = b.indexOf(item);
        if (i === -1) return sum + 1;
        b.splice(i, 1);
        return sum;
    }, 0);
}

The one with the lowest score has the most similarity, eg

diff(me, buns) // 1
diff(me, duns) // 2
// `buns` is more like `me` than `duns`

Please note that these are not commutative operations when the length of the Array is not the same; diff(a, b) may be different to diff(b, a) when a.length !== b.length
If you want to compare the results you need the common array on the same side of all tests

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM