findClosestMatch(value, candidates, threshold) compares a value to a list of candidates with normalized Levenshtein distance (trimmed, case-insensitive). It returns {match, score} for the closest candidate whose score is at least threshold, or null if nothing is close enough. Score is 1 - distance / max(length), so 1 is an exact match after normalization.
When to use
- Catching typo variants of a name before they split a report (
Ada LovelcevsAda Lovelace) - Suggesting a standard client name from a roster
- Any merge where a person should confirm the suggestion
How to use this snippet
/**
* Closest candidate by normalized Levenshtein score (0–1, 1 = exact after trim/case).
* Returns {match, score} if score >= threshold, else null.
* threshold defaults to 0 (always return the closest non-empty candidate).
* Ties go to the earlier candidate. The original candidate string is returned.
*
* @param {*} value
* @param {Array} candidates
* @param {number} [threshold=0]
* @return {{match: string, score: number}|null}
*/
function findClosestMatch(value, candidates, threshold) {
var needle = String(value == null ? '' : value).trim().toLowerCase();
if (!needle || !candidates || !candidates.length) return null;
if (threshold == null) threshold = 0;
var best = null;
var bestScore = -1;
for (var i = 0; i < candidates.length; i++) {
var cand = candidates[i] == null ? '' : String(candidates[i]);
var norm = cand.trim().toLowerCase();
if (!norm) continue;
var maxLen = Math.max(needle.length, norm.length);
var score = maxLen ? 1 - (levenshteinDistance_(needle, norm) / maxLen) : 1;
if (score > bestScore) {
bestScore = score;
best = cand;
}
}
if (best == null || bestScore < threshold) return null;
return { match: best, score: bestScore };
}
function levenshteinDistance_(a, b) {
var n = a.length, m = b.length;
if (!n) return m;
if (!m) return n;
var prev = new Array(m + 1);
var cur = new Array(m + 1);
for (var j = 0; j <= m; j++) prev[j] = j;
for (var i = 1; i <= n; i++) {
cur[0] = i;
for (var j = 1; j <= m; j++) {
var cost = a.charAt(i - 1) === b.charAt(j - 1) ? 0 : 1;
cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost);
}
var tmp = prev; prev = cur; cur = tmp;
}
return prev[m];
}
Example
function suggestClient(name) {
var roster = ['Ada Lovelace', 'Grace Hopper', 'Alan Turing'];
return findClosestMatch(name, roster, 0.8);
}
// suggestClient('Ada Lovelce') → {match: 'Ada Lovelace', score: 0.916…}
Notes
- This catches spelling typos. It will not treat
Smith, JonandJon Smithas close — word order is a different problem. - Pick a threshold and look at real misses on a copy before you automate anything.
0.8is a reasonable starting point for short names; lower it only if you are prepared to review more false hits. - Return
nullrather than guessing when the score is below the threshold. A human should confirm each merge.
Happy Coding!
