You could use a filter to find all items that contain each string, keeping track of the count and the position of those that do to find the first one that has the most matches.
Something like:
var groupArray = [
['10', 'group one result'],
['10 20 30', 'group two result'],
['10 20 40', 'group three result']
];
function compare(entryArr, stringArr) {
let pos = 0;
let matches = 0;
for (var i in entryArr) {
str = stringArr.split(' ');
ent = entryArr[i][0].split(' ');
let f = str.filter(s => ent.includes(s));
if (f)
if (f.length > matches) {
pos = i;
matches = f.length;
}
}
if (matches > 0) {
return entryArr[pos].slice(1);
} else {
return [];
}
}
//find match from possible strings
console.log(compare(groupArray, '10')) // returns first entry that matches one value - group one result
console.log(compare(groupArray, '10 20')) // returns first entry that matches both values - group two result
console.log(compare(groupArray, '10 20 60')) // returns first entry with 2 matches - group two result
console.log(compare(groupArray, '50 60 80')) // no matches, returns empty array
** UPDATE: to return multiple group names where matches have been found, ordered by match count then by group numbers **
var groupArray = [
['10', 'group one result', 'more one result'],
['10 20 40', 'group three result'],
['10 20 30', 'group two result'],
['10 20 30 40', 'group four result'],
['20 60', 'group five result']
];
function compare(entryArr, stringArr) {
// Array to hold ALL matches found
let matched = [];
// Loop through the entryArry array
for (let i = 0; i < entryArr.length; i++) {
// split search string into separate values
str = stringArr.split(' ');
// split the main array into separate values
ent = entryArr[i][0].split(' ');
// find any main array items that contain the search string values
let f = str.filter(s => ent.includes(s));
// If found...
if (f.length > 0) {
//... push into the matched array
matched.push([f.length, ...entryArr[i]]);
}
}
// If we have more than one match found, sort the matched array
// First by match count descending, then by the main array values, ascending
if (matched.length > 1) {
matched.sort(function(a, b){
if (a[0] == b[0]) {
return a[1] > b[1];
} else {
return a[0] < b[0];
}
})
// Now remove the unnecessary parts of each match
// We only want the group name, not the match count or the group's numbers string
for (let i = 0; i < matched.length; i++) {
matched[i] = matched[i].slice(2);
}
}
// return the result
return matched;
}
//find match from possible strings
console.log(compare(groupArray, '10'));
console.log(compare(groupArray, '10 20'));
console.log(compare(groupArray, '10 20 60'));
console.log(compare(groupArray, '20 30 40'));
CLICK HERE to find out more related problems solutions.