Top Related Projects
Lightweight fuzzy-search, in JavaScript
:crystal_ball: Tiny and blazing-fast fuzzy search in JavaScript
fuzzyset.js - A fuzzy string set for javascript
Simple, expected, and deterministic best-match sorting of an array in JavaScript
Quick Overview
Fuzzysort is a fast, lightweight JavaScript fuzzy search library. It provides efficient and accurate fuzzy matching for strings, making it ideal for implementing search functionality in web applications or command-line interfaces.
Pros
- Fast performance, even with large datasets
- Lightweight with no dependencies
- Supports both browser and Node.js environments
- Customizable scoring and highlighting options
Cons
- Limited to string-based searches
- May not be suitable for complex search scenarios
- Documentation could be more comprehensive
- No built-in support for asynchronous operations
Code Examples
Basic fuzzy search:
import fuzzysort from 'fuzzysort'
const result = fuzzysort.single('al', 'apple')
console.log(result.score) // Output: 0
console.log(result.target) // Output: 'apple'
Searching through an array of strings:
const fruits = ['apple', 'banana', 'orange', 'pear']
const results = fuzzysort.go('an', fruits)
console.log(results.map(r => r.target)) // Output: ['banana', 'orange']
Custom key search on objects:
const books = [
{ title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' },
{ title: 'To Kill a Mockingbird', author: 'Harper Lee' }
]
const results = fuzzysort.go('kill', books, {key: 'title'})
console.log(results[0].obj.title) // Output: 'To Kill a Mockingbird'
Getting Started
-
Install fuzzysort:
npm install fuzzysort
-
Import and use in your project:
import fuzzysort from 'fuzzysort' const searchTerm = 'fzz' const targets = ['fuzzy', 'fuzzysort', 'algorithm'] const results = fuzzysort.go(searchTerm, targets) console.log(results.map(r => r.target))
-
For more advanced usage, refer to the GitHub repository for additional options and configurations.
Competitor Comparisons
Lightweight fuzzy-search, in JavaScript
Pros of Fuse
- More comprehensive and feature-rich fuzzy search library
- Supports searching through objects and nested properties
- Offers more customization options for search behavior
Cons of Fuse
- Generally slower performance compared to fuzzysort
- Larger file size, which may impact load times in web applications
- More complex API, potentially requiring a steeper learning curve
Code Comparison
Fuse:
const fuse = new Fuse(list, {
keys: ['title', 'author.firstName']
})
const result = fuse.search('old man')
fuzzysort:
const results = fuzzysort.go('old man', list, {
keys: ['title', 'author.firstName']
})
Both libraries offer similar basic functionality, but Fuse provides more advanced options for configuring the search behavior. fuzzysort's API is simpler and more straightforward, which may be preferable for simpler use cases.
While Fuse offers more features and flexibility, fuzzysort focuses on speed and simplicity. The choice between the two depends on the specific requirements of your project, such as the need for advanced search capabilities versus performance optimization.
:crystal_ball: Tiny and blazing-fast fuzzy search in JavaScript
Pros of fuzzysearch
- Lightweight and simple implementation
- Supports searching with typos and character transpositions
- Works well for small to medium-sized datasets
Cons of fuzzysearch
- Less optimized for large datasets compared to fuzzysort
- Fewer advanced features and customization options
- May not perform as well for complex sorting scenarios
Code Comparison
fuzzysearch:
function fuzzysearch (needle, haystack) {
var hlen = haystack.length;
var nlen = needle.length;
if (nlen > hlen) {
return false;
}
// ... (additional implementation)
}
fuzzysort:
function fuzzysort(search, target, options) {
if (!search) return null
if (!target) return null
var preparedSearch = fuzzysort.prepareSearch(search)
var searchLowerCode = search[0].toLowerCase().charCodeAt(0)
// ... (additional implementation)
}
Both libraries provide fuzzy searching functionality, but fuzzysort offers more advanced features and optimizations for larger datasets. fuzzysearch is simpler and more lightweight, making it suitable for smaller projects or when minimal dependencies are desired. fuzzysort provides better performance for complex sorting scenarios and larger datasets, but may be overkill for simpler use cases.
fuzzyset.js - A fuzzy string set for javascript
Pros of fuzzyset.js
- Supports more advanced fuzzy matching techniques, including Levenshtein distance
- Provides a confidence score for matches, allowing for more fine-grained control
- Can handle larger datasets efficiently due to its indexing approach
Cons of fuzzyset.js
- Generally slower performance compared to fuzzysort, especially for simpler matching tasks
- More complex API, which may be overkill for basic fuzzy search needs
- Larger file size, potentially impacting load times in web applications
Code Comparison
fuzzyset.js:
const FuzzySet = require('fuzzyset.js');
const set = FuzzySet(['apple', 'banana', 'orange']);
const result = set.get('aple');
console.log(result); // [[0.8, 'apple']]
fuzzysort:
const fuzzysort = require('fuzzysort');
const fruits = ['apple', 'banana', 'orange'];
const result = fuzzysort.go('aple', fruits);
console.log(result[0].target); // 'apple'
Both libraries offer fuzzy string matching capabilities, but they differ in their approach and use cases. fuzzyset.js provides more advanced matching techniques and confidence scores, making it suitable for complex fuzzy matching scenarios. However, it comes at the cost of performance and simplicity. fuzzysort, on the other hand, offers a simpler API and faster performance, making it ideal for basic fuzzy search functionality in applications where speed is crucial.
Simple, expected, and deterministic best-match sorting of an array in JavaScript
Pros of match-sorter
- More flexible ranking system with customizable criteria
- Supports internationalization and diacritics
- Better documentation and examples
Cons of match-sorter
- Slightly slower performance for large datasets
- More complex API, which may be overkill for simple use cases
Code Comparison
match-sorter:
import matchSorter from 'match-sorter'
const results = matchSorter(list, 'query', {
keys: ['name', 'email'],
threshold: matchSorter.rankings.CONTAINS
})
fuzzysort:
import fuzzysort from 'fuzzysort'
const results = fuzzysort.go('query', list, {
keys: ['name', 'email']
})
Both libraries provide fuzzy searching capabilities, but match-sorter offers more advanced features and customization options. It supports multiple ranking criteria and internationalization, making it suitable for complex search scenarios. However, this comes at the cost of slightly lower performance and a more complex API.
fuzzysort, on the other hand, is designed for simplicity and speed. It's more lightweight and performs better with large datasets, but lacks some of the advanced features found in match-sorter.
The choice between the two depends on the specific requirements of your project, balancing between flexibility and performance.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Fast, Tiny, & Good fuzzy search for JavaScript.
Fast: <1ms to search 13,000 files.
Tiny: 1 file, 0 dependencies, 5kb.
Good: clean api + sorts results well.
Demo
https://rawgit.com/farzher/fuzzysort/master/test/test.html
Installation Node / Bun / Deno
npm i fuzzysort
import fuzzysort from 'fuzzysort'
const fuzzysort = require('fuzzysort')
Installation Browser
<script src="https://cdn.jsdelivr.net/npm/fuzzysort@3.0.2/fuzzysort.min.js"></script>
Usage
fuzzysort.go(search, targets, options=null)
const mystuff = [{file: 'Apple.cpp'}, {file: 'Banana.cpp'}]
const results = fuzzysort.go('a', mystuff, {key: 'file'})
// [{score: 0.81, obj: {file: 'Apple.cpp'}}, {score: 0.59, obj: {file: 'Banana.cpp'}}]
Options
fuzzysort.go(search, targets, {
threshold: 0, // Don't return matches worse than this
limit: 0, // Don't return more results than this
all: false, // If true, returns all results for an empty search
key: null, // For when targets are objects (see its example usage)
keys: null, // For when targets are objects (see its example usage)
scoreFn: null, // For use with `keys` (see its example usage)
})
What's a result
const result = fuzzysort.single('query', 'some string that contains my query.')
result.score // .80 (1 is a perfect match. 0.5 is a good match. 0 is no match.)
result.target // 'some string that contains my query.'
result.obj // reference to your original obj when using options.key
result.indexes // [29, 30, 31, 32, 33]
result.highlight('<b>', '</b>')
// 'some string that contains my <b>query</b>.'
result.highlight((m, i) => <react key={i}>{m}</react>)
//Â ['some string that contains my ', <react key=0>query</react>, '.']
Advanced Usage
Search a list of objects, by multiple complex keys, with custom weights.
let objects = [{
title: 'Liechi Berry',
meta: {desc: 'Raises Attack when HP is low.'},
tags: ['berries', 'items'],
bookmarked: true,
}, {
title: 'Petaya Berry',
meta: {desc: 'Raises Special Attack when HP is low.'},
}]
let results = fuzzysort.go('attack berry', objects, {
keys: ['title', 'meta.desc', obj => obj.tags?.join()],
scoreFn: r => r.score * r.obj.bookmarked ? 2 : 1, // if the item is bookmarked, boost its score
})
var keysResult = results[0]
// When using multiple `keys`, results are different. They're indexable to get each normal result
keysResult[0].highlight() // 'Liechi <b>Berry</b>'
keysResult[1].highlight() // 'Raises <b>Attack</b> when HP is low.'
keysResult.score // .84
keysResult.obj.title // 'Liechi Berry'
How To Go Fast · Performance Tips
let targets = [{file: 'Monitor.cpp'}, {file: 'MeshRenderer.cpp'}]
// filter out targets that you don't need to search! especially long ones!
targets = targets.filter(t => t.file.length < 1000)
// if your targets don't change often, provide prepared targets instead of raw strings!
targets.forEach(t => t.filePrepared = fuzzysort.prepare(t.file))
// don't use options.key if you don't need a reference to your original obj
targets = targets.map(t => t.filePrepared)
const options = {
limit: 100, // don't return more results than you need!
threshold: .5, // don't return bad results
}
fuzzysort.go('gotta', targets, options)
fuzzysort.go('go', targets, options)
fuzzysort.go('fast', targets, options)
Gotcha
result.score
is implemented as a getter/setter and stored different internally
r.score = .3; // r.score == 0.30000000000000004
Star History
Changelog
v3.0.0
- Added new behavior when using
keys
and your search contains spaces! - Added
options.key
can now be a function{key: obj => obj.tags.join()}
- Removed
fuzzysort.indexes
& Addedresult.indexes
(as a getter/setter for GC perf) - Removed
fuzzysort.highlight()
& Addedresult.highlight()
- Changed scoring: score is now a number from 0 to 1 instead of from -Infinity to 0
- Changed scoring: substring matches are even more relevant
- Changed scoring:
straw berry
now matches great againststrawberry
- Changed scoring: tweaked the scoring quite a bit
result.score
is behind a getter/setter for performance reasons- Fixed minor issues
v2.0.0
- Added new behavior when your search contains spaces!
- Added fuzzysort.min.js
- Now depends on ES6 features
- Removed
result.indexes
& Addedfuzzysort.indexes
(improved GC performance) - Completely Removed
options.allowTypo
- Completely Removed
fuzzysort.goAsync
- Completely Removed
fuzzysort.new
- Rewrote the demo
v1.9.0
- Even faster
- Added
options.all
- Deprecated/Removed
options.allowTypo
- Deprecated/Removed
fuzzysort.goAsync
- Changed scoring: boosted substring matches
- Changed scoring: targets with too many beginning indexes lose points for being a bad target
- Changed scoring: penality for not starting near the beginning
- Changed scoring: penality for more groups
- Fixed "Exponential backtracking hangs browser"
v1.2.0
- Added
fuzzysort.highlight(result, callback)
v1.1.0
- Added
allowTypo
as an option
v1.0.0
- Inverted scores; they're now negative instead of positive, so that higher scores are better
- Added ability to search objects by
key
/keys
with custom weights - Removed the option to automatically highlight and exposed
fuzzysort.highlight
- Removed all options from
fuzzysort
and moved them intofuzzysort.go
optional params
v0.x.x
- init
Top Related Projects
Lightweight fuzzy-search, in JavaScript
:crystal_ball: Tiny and blazing-fast fuzzy search in JavaScript
fuzzyset.js - A fuzzy string set for javascript
Simple, expected, and deterministic best-match sorting of an array in JavaScript
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot