levenshtein | Find the levenshtein distance | search levenshtein distance | Search

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.

Run example

npm run import -- "Sort by levenshtein distance"

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;

What the code could have been:

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:

  1. Import:

  2. levSort Function:

  3. Sorting Logic:

  4. Return Value: