The levSort
function sorts an array of objects based on how similar their strings are to a given search string, using the Levenshtein distance as the similarity measure.
npm run import -- "Sort by levenshtein distance"
var importer = require('../Core');
var levDist = importer.import().levDist;
function levSort(arr, search, getStr) {
if(typeof getStr === 'undefined') {
getStr = (a) => a;
}
var result = arr.map((a) => a); // make a copy of the array
result.sort(function (a, b) {
return levDist(getStr(a), search) - levDist(getStr(b), search);
});
return result;
}
module.exports = levSort;
const { levDist } = require('../Core');
/**
* Sorts an array of items based on the Levenshtein distance to a search term.
*
* @param {array} arr The array of items to sort.
* @param {string} search The search term to compare against.
* @param {function} [getStr = a => a] A function to extract the string to compare from each item.
* @returns {array} The sorted array.
*/
function levSort(arr, search, getStr = a => a) {
// Make a copy of the array to avoid modifying the original
const result = [...arr];
// Sort the array based on the Levenshtein distance
result.sort((a, b) =>
// Calculate the Levenshtein distance to the search term
levDist(getStr(a), search) - levDist(getStr(b), search)
);
// Return the sorted array
return result;
}
module.exports = levSort;
This code defines a function called levSort
that sorts an array of objects based on their Levenshtein distance to a given search string.
Here's a breakdown:
Import:
levDist
function from a module located at ../Core
. This function calculates the Levenshtein distance between two strings.levSort
Function:
arr
: The array to be sorted.search
: The string to compare against.getStr
: An optional function to extract a string from each object in the array. If not provided, it defaults to returning the object itself.Sorting Logic:
arr
to avoid modifying the original.sort
method with a custom comparison function.getStr(a)
and getStr(b)
) and the search
string.Return Value: