• Stars
    star
    3,719
  • Rank 11,871 (Top 0.3 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 8 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simple, expected, and deterministic best-match sorting of an array in JavaScript

match-sorter

Simple, expected, and deterministic best-match sorting of an array in JavaScript


Demo

Build Status Code Coverage version downloads MIT License All Contributors PRs Welcome Code of Conduct Examples

The problem

  1. You have a list of dozens, hundreds, or thousands of items
  2. You want to filter and sort those items intelligently (maybe you have a filter input for the user)
  3. You want simple, expected, and deterministic sorting of the items (no fancy math algorithm that fancily changes the sorting as they type)

This solution

This follows a simple and sensible (user friendly) algorithm that makes it easy for you to filter and sort a list of items based on given input. Items are ranked based on sensible criteria that result in a better user experience.

To explain the ranking system, I'll use countries as an example:

  1. CASE SENSITIVE EQUALS: Case-sensitive equality trumps all. These will be first. (ex. France would match France, but not france)
  2. EQUALS: Case-insensitive equality (ex. France would match france)
  3. STARTS WITH: If the item starts with the given value (ex. Sou would match South Korea or South Africa)
  4. WORD STARTS WITH: If the item has multiple words, then if one of those words starts with the given value (ex. Repub would match Dominican Republic)
  5. CONTAINS: If the item contains the given value (ex. ham would match Bahamas)
  6. ACRONYM: If the item's acronym is the given value (ex. us would match United States)
  7. SIMPLE MATCH: If the item has letters in the same order as the letters of the given value (ex. iw would match Zimbabwe, but not Kuwait because it must be in the same order). Furthermore, if the item is a closer match, it will rank higher (ex. ua matches Uruguay more closely than United States of America, therefore Uruguay will be ordered before United States of America)

This ranking seems to make sense in people's minds. At least it does in mine. Feedback welcome!

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's dependencies:

npm install match-sorter

Usage

import {matchSorter} from 'match-sorter'
// or const {matchSorter} = require('match-sorter')
// or window.matchSorter.matchSorter
const list = ['hi', 'hey', 'hello', 'sup', 'yo']
matchSorter(list, 'h') // ['hello', 'hey', 'hi']
matchSorter(list, 'y') // ['yo', 'hey']
matchSorter(list, 'z') // []

Advanced options

keys: [string]

Default: undefined

By default it just uses the value itself as above. Passing an array tells match-sorter which keys to use for the ranking.

const objList = [
  {name: 'Janice', color: 'Green'},
  {name: 'Fred', color: 'Orange'},
  {name: 'George', color: 'Blue'},
  {name: 'Jen', color: 'Red'},
]
matchSorter(objList, 'g', {keys: ['name', 'color']})
// [{name: 'George', color: 'Blue'}, {name: 'Janice', color: 'Green'}, {name: 'Fred', color: 'Orange'}]

matchSorter(objList, 're', {keys: ['color', 'name']})
// [{name: 'Jen', color: 'Red'}, {name: 'Janice', color: 'Green'}, {name: 'Fred', color: 'Orange'}, {name: 'George', color: 'Blue'}]

Array of values: When the specified key matches an array of values, the best match from the values of in the array is going to be used for the ranking.

const iceCreamYum = [
  {favoriteIceCream: ['mint', 'chocolate']},
  {favoriteIceCream: ['candy cane', 'brownie']},
  {favoriteIceCream: ['birthday cake', 'rocky road', 'strawberry']},
]
matchSorter(iceCreamYum, 'cc', {keys: ['favoriteIceCream']})
// [{favoriteIceCream: ['candy cane', 'brownie']}, {favoriteIceCream: ['mint', 'chocolate']}]

Nested Keys: You can specify nested keys using dot-notation.

const nestedObjList = [
  {name: {first: 'Janice'}},
  {name: {first: 'Fred'}},
  {name: {first: 'George'}},
  {name: {first: 'Jen'}},
]
matchSorter(nestedObjList, 'j', {keys: ['name.first']})
// [{name: {first: 'Janice'}}, {name: {first: 'Jen'}}]

const nestedObjList = [
  {name: [{first: 'Janice'}]},
  {name: [{first: 'Fred'}]},
  {name: [{first: 'George'}]},
  {name: [{first: 'Jen'}]},
]
matchSorter(nestedObjList, 'j', {keys: ['name.0.first']})
// [{name: {first: 'Janice'}}, {name: {first: 'Jen'}}]

// matchSorter(nestedObjList, 'j', {keys: ['name[0].first']}) does not work

This even works with arrays of multiple nested objects: just specify the key using dot-notation with the * wildcard instead of a numeric index.

const nestedObjList = [
  {aliases: [{name: {first: 'Janice'}},{name: {first: 'Jen'}}]},
  {aliases: [{name: {first: 'Fred'}},{name: {first: 'Frederic'}}]},
  {aliases: [{name: {first: 'George'}},{name: {first: 'Georgie'}}]},
]
matchSorter(nestedObjList, 'jen', {keys: ['aliases.*.name.first']})
// [{aliases: [{name: {first: 'Janice'}},{name: {first: 'Jen'}}]}]
matchSorter(nestedObjList, 'jen', {keys: ['aliases.0.name.first']})
// []

Property Callbacks: Alternatively, you may also pass in a callback function that resolves the value of the key(s) you wish to match on. This is especially useful when interfacing with libraries such as Immutable.js

const list = [{name: 'Janice'}, {name: 'Fred'}, {name: 'George'}, {name: 'Jen'}]
matchSorter(list, 'j', {keys: [item => item.name]})
// [{name: 'Janice'}, {name: 'Jen'}]

For more complex structures, expanding on the nestedObjList example above, you can use map:

const nestedObjList = [
  {
    name: [
      {first: 'Janice', last: 'Smith'},
      {first: 'Jon', last: 'Doe'},
    ],
  },
  {
    name: [
      {first: 'Fred', last: 'Astaire'},
      {first: 'Jenny', last: 'Doe'},
      {first: 'Wilma', last: 'Flintstone'},
    ],
  },
]
matchSorter(nestedObjList, 'doe', {
  keys: [
    item => item.name.map(i => i.first),
    item => item.name.map(i => i.last),
  ],
})
// [name: [{ first: 'Janice', last: 'Smith' },{ first: 'Jon', last: 'Doe' }], name: [{ first: 'Fred', last: 'Astaire' },{ first: 'Jenny', last: 'Doe' },{ first: 'Wilma', last: 'Flintstone' }]]

Threshold: You may specify an individual threshold for specific keys. A key will only match if it meets the specified threshold. For more information regarding thresholds see below

const list = [
  {name: 'Fred', color: 'Orange'},
  {name: 'Jen', color: 'Red'},
]
matchSorter(list, 'ed', {
  keys: [{threshold: matchSorter.rankings.STARTS_WITH, key: 'name'}, 'color'],
})
//[{name: 'Jen', color: 'Red'}]

Min and Max Ranking: You may restrict specific keys to a minimum or maximum ranking by passing in an object. A key with a minimum rank will only get promoted if there is at least a simple match.

const tea = [
  {tea: 'Earl Grey', alias: 'A'},
  {tea: 'Assam', alias: 'B'},
  {tea: 'Black', alias: 'C'},
]
matchSorter(tea, 'A', {
  keys: ['tea', {maxRanking: matchSorter.rankings.STARTS_WITH, key: 'alias'}],
})
// without maxRanking, Earl Grey would come first because the alias "A" would be CASE_SENSITIVE_EQUAL
// `tea` key comes before `alias` key, so Assam comes first even though both match as STARTS_WITH
// [{tea: 'Assam', alias: 'B'}, {tea: 'Earl Grey', alias: 'A'},{tea: 'Black', alias: 'C'}]
const tea = [
  {tea: 'Milk', alias: 'moo'},
  {tea: 'Oolong', alias: 'B'},
  {tea: 'Green', alias: 'C'},
]
matchSorter(tea, 'oo', {
  keys: ['tea', {minRanking: matchSorter.rankings.EQUAL, key: 'alias'}],
})
// minRanking bumps Milk up to EQUAL from CONTAINS (alias)
// Oolong matches as STARTS_WITH
// Green is missing due to no match
// [{tea: 'Milk', alias: 'moo'}, {tea: 'Oolong', alias: 'B'}]

threshold: number

Default: MATCHES

Thresholds can be used to specify the criteria used to rank the results. Available thresholds (from top to bottom) are:

  • CASE_SENSITIVE_EQUAL
  • EQUAL
  • STARTS_WITH
  • WORD_STARTS_WITH
  • STRING_CASE
  • STRING_CASE_ACRONYM
  • CONTAINS
  • ACRONYM
  • MATCHES (default value)
  • NO_MATCH
const fruit = ['orange', 'apple', 'grape', 'banana']
matchSorter(fruit, 'ap', {threshold: matchSorter.rankings.NO_MATCH})
// ['apple', 'grape', 'orange', 'banana'] (returns all items, just sorted by best match)

const things = ['google', 'airbnb', 'apple', 'apply', 'app'],
matchSorter(things, 'app', {threshold: matchSorter.rankings.EQUAL})
// ['app'] (only items that are equal)

const otherThings = ['fiji apple', 'google', 'app', 'crabapple', 'apple', 'apply']
matchSorter(otherThings, 'app', {threshold: matchSorter.rankings.WORD_STARTS_WITH})
// ['app', 'apple', 'apply', 'fiji apple'] (everything that matches with "word starts with" or better)

keepDiacritics: boolean

Default: false

By default, match-sorter will strip diacritics before doing any comparisons. This is the default because it makes the most sense from a UX perspective.

You can disable this behavior by specifying keepDiacritics: true

const thingsWithDiacritics = [
  'jalapeño',
  'à la carte',
  'café',
  'papier-mâché',
  'à la mode',
]
matchSorter(thingsWithDiacritics, 'aa')
// ['jalapeño', 'à la carte', 'à la mode', 'papier-mâché']

matchSorter(thingsWithDiacritics, 'aa', {keepDiacritics: true})
// ['jalapeño', 'à la carte']

matchSorter(thingsWithDiacritics, 'à', {keepDiacritics: true})
// ['à la carte', 'à la mode']

baseSort: function(itemA, itemB): -1 | 0 | 1

Default: (a, b) => String(a.rankedValue).localeCompare(b.rankedValue)

By default, match-sorter uses the String.localeCompare function to tie-break items that have the same ranking. This results in a stable, alphabetic sort.

const list = ['C apple', 'B apple', 'A apple']
matchSorter(list, 'apple')
// ['A apple', 'B apple', 'C apple']

You can customize this behavior by specifying a custom baseSort function:

const list = ['C apple', 'B apple', 'A apple']
// This baseSort function will use the original index of items as the tie breaker
matchSorter(list, 'apple', {baseSort: (a, b) => (a.index < b.index ? -1 : 1)})
// ['C apple', 'B apple', 'A apple']

sorter: function(rankedItems): rankedItems

Default: matchedItems => matchedItems.sort((a, b) => sortRankedValues(a, b, baseSort))

By default, match-sorter uses an internal sortRankedValues function to sort items after matching them.

You can customize the core sorting behavior by specifying a custom sorter function:

Disable sorting entirely:

const list = ['appl', 'C apple', 'B apple', 'A apple', 'app', 'applebutter']
matchSorter(list, 'apple', {sorter: rankedItems => rankedItems})
// ['C apple', 'B apple', 'A apple', 'applebutter']

Return the unsorted rankedItems, but in reverse order:

const list = ['appl', 'C apple', 'B apple', 'A apple', 'app', 'applebutter']
matchSorter(list, 'apple', {sorter: rankedItems => [...rankedItems].reverse()})
// ['applebutter', 'A apple', 'B apple', 'C apple']

Recipes

Match PascalCase, camelCase, snake_case, or kebab-case as words

By default, match-sorter assumes spaces to be the word separator. However, if your data has a different word separator, you can use a property callback to replace your separator with spaces. For example, for snake_case:

const list = [
  {name: 'Janice_Kurtis'},
  {name: 'Fred_Mertz'},
  {name: 'George_Foreman'},
  {name: 'Jen_Smith'},
]
matchSorter(list, 'js', {keys: [item => item.name.replace(/_/g, ' ')]})
// [{name: 'Jen_Smith'}, {name: 'Janice_Kurtis'}]

Match many words across multiple fields (table filtering)

By default, match-sorter will return matches from objects where one of the properties matches the entire search term. For multi-column data sets it can be beneficial to split words in search string and match each word separately. This can be done by chaining match-sorter calls.

The benefit of this is that a filter string of "two words" will match both "two" and "words", but will return rows where the two words are found in different columns as well as when both words match in the same column. For single-column matches it will also return matches out of order (column = "wordstwo" will match just as well as column="twowords", the latter getting a higher score).

function fuzzySearchMultipleWords(
  rows, // array of data [{a: "a", b: "b"}, {a: "c", b: "d"}]
  keys, // keys to search ["a", "b"]
  filterValue: string, // potentially multi-word search string "two words"
) {
  if (!filterValue || !filterValue.length) {
    return rows
  }

  const terms = filterValue.split(' ')
  if (!terms) {
    return rows
  }

  // reduceRight will mean sorting is done by score for the _first_ entered word.
  return terms.reduceRight(
    (results, term) => matchSorter(results, term, {keys}),
    rows,
  )
}

Multi-column code sandbox

Inspiration

Actually, most of this code was extracted from the very first library I ever wrote: genie!

Other Solutions

You might try Fuse.js. It uses advanced math fanciness to get the closest match. Unfortunately what's "closest" doesn't always really make sense. So I extracted this from genie.

Issues

Looking to contribute? Look for the Good First Issue label.

🐛 Bugs

Please file an issue for bugs, missing documentation, or unexpected behavior.

See Bugs

💡 Feature Requests

Please file an issue to suggest new features. Vote on feature requests by adding a 👍. This helps maintainers prioritize what to work on.

See Feature Requests

Contributors

Thanks goes to these people (emoji key):


Kent C. Dodds

💻 📖 🚇 ⚠️ 👀

Conor Hastings

💻 📖 ⚠️ 👀

Rogelio Guzman

📖

Claudéric Demers

💻 📖 ⚠️

Kevin Davis

💻 ⚠️

Denver Chen

💻 📖 ⚠️

Christian Ruigrok

🐛 💻 📖

Hozefa

🐛 💻 ⚠️ 🤔

pushpinder107

💻

Mordy Tikotzky

💻 📖 ⚠️

Steven Brannum

💻 ⚠️

Christer van der Meeren

🐛

Samuel Petrosyan

💻 🐛

Brandon Kalinowski

🐛

Eric Berry

🔍

Skubie Doo

📖

Michaël De Boey

💻 👀

Tanner Linsley

💻 ⚠️

Victor

📖

Rebecca Stevens

🐛 📖

Marco Moretti

📖

Ricardo Busquet

🤔 👀 💻

Weyert de Boer

🤔 👀

Philipp Garbowsky

💻

Mart

💻 ⚠️ 📖

Aleksey Levenstein

💻

Take Weiland

💻

Amit Abershitz

📖

This project follows the all-contributors specification. Contributions of any kind welcome!

LICENSE

MIT

More Repositories

1

cross-env

🔀 Cross platform setting of environment scripts
JavaScript
6,313
star
2

advanced-react-patterns

This is the latest advanced react patterns workshop
JavaScript
2,885
star
3

babel-plugin-macros

🎣 Allows you to build simple compile-time libraries
JavaScript
2,622
star
4

react-hooks

Learn React Hooks! 🎣 ⚛
JavaScript
2,550
star
5

bookshelf

Build a ReactJS App workshop
JavaScript
2,533
star
6

kentcdodds.com

My personal website
MDX
2,143
star
7

use-deep-compare-effect

🐋 It's react's useEffect hook, except using deep comparison on the inputs, not reference equality
TypeScript
1,726
star
8

mdx-bundler

🦤 Give me MDX/TSX strings and I'll give you back a component you can render. Supports imports!
JavaScript
1,702
star
9

react-performance

Let's make our apps fast ⚡
JavaScript
1,557
star
10

advanced-react-patterns-v2

Created with CodeSandbox
JavaScript
1,499
star
11

testing-workshop

A workshop for learning how to test JavaScript applications
JavaScript
1,363
star
12

babel-plugin-preval

🐣 Pre-evaluate code at build-time
TypeScript
1,357
star
13

advanced-react-patterns-v1

The course material for my advanced react patterns course on Egghead.io
HTML
1,092
star
14

react-testing-library-course

Test React Components with Jest and React Testing Library on TestingJavaScript.com
JavaScript
1,004
star
15

testing-react-apps

A workshop for testing react applications
JavaScript
977
star
16

kcd-scripts

CLI toolbox for common scripts for my projects
JavaScript
870
star
17

stop-runaway-react-effects

🏃 Catches situations when a react use(Layout)Effect runs repeatedly in rapid succession
JavaScript
788
star
18

netlify-shortener

Your own free URL shortener with Netlify
JavaScript
778
star
19

beginners-guide-to-react

The Beginner's Guide To ReactJS
HTML
757
star
20

react-suspense

React Suspense workshop
JavaScript
746
star
21

old-kentcdodds.com

Kent's Homepage
JavaScript
736
star
22

ng-stats

Little utility to show stats about your page's angular digest/watches.
JavaScript
657
star
23

dotfiles

Shell
510
star
24

js-testing-fundamentals

Fundamentals of Testing in JavaScript on TestingJavaScript.com
JavaScript
500
star
25

react-toggled

Component to build simple, flexible, and accessible toggle components
JavaScript
453
star
26

jest-cypress-react-babel-webpack

Configure Jest for Testing JavaScript Applications and Install, Configure, and Script Cypress for JavaScript Web Applications on TestingJavaScript.com
JavaScript
442
star
27

advanced-remix

TypeScript
393
star
28

react-testing-library-examples

Created with CodeSandbox
HTML
380
star
29

testing-node-apps

Test Node.js Backends on TestingJavaScript.com
JavaScript
365
star
30

es6-workshop

A very hands on 👐 workshop 💻 about ES6 and beyond.
JavaScript
362
star
31

es6-todomvc

The vanillajs example converted to es6
JavaScript
353
star
32

babel-plugin-codegen

💥 Generate code at build-time
TypeScript
347
star
33

eslint-config-kentcdodds

ESLint configuration for projects that I do... Feel free to use this!
JavaScript
338
star
34

cloc

An npm module for distributing cloc by Al Danial
JavaScript
325
star
35

asts-workshop

Improved productivity 💯 with the practical 🤓 use of the power 💪 of Abstract Syntax Trees 🌳 to lint ⚠️ and transform 🔀 your code
JavaScript
295
star
36

how-jest-mocking-works

JavaScript
294
star
37

js-mocking-fundamentals

JavaScript Mocking Fundamentals on TestingJavaScript.com
JavaScript
281
star
38

webpack-config-utils

Utilities to help your webpack config be easier to read
JavaScript
262
star
39

express-app-example

How I structure Express Apps (example repo)
JavaScript
261
star
40

dom-testing-library-with-anything

Use DOM Testing Library to test any JS framework on TestingJavaScript.com
JavaScript
217
star
41

learn-react

Learn React with a laser focused, guided approach.
JavaScript
213
star
42

the-webs-next-transition

TypeScript
211
star
43

modern-react

workshop about React's hottest new features in 16.7.0
JavaScript
207
star
44

react-jest-workshop

JavaScript
199
star
45

react-github-profile

JavaScript
199
star
46

react-ava-workshop

🐯 A workshop repository for testing React ⚛ with AVA 🚀 --> slides
JavaScript
192
star
47

api-check

VanillaJS version of ReactJS propTypes
JavaScript
191
star
48

starwars-names

Get a random Star Wars name
JavaScript
185
star
49

import-all.macro

A babel-macro that allows you to import all files that match a glob
JavaScript
177
star
50

remix-todomvc

An Implementation of TodoMVC with Remix
TypeScript
172
star
51

rtl-css-js

RTL for CSS in JS
JavaScript
162
star
52

react-workshop-app

An abstraction for all my React workshops
TypeScript
144
star
53

generator-kcd-oss

A yeoman generator for my open source modules
JavaScript
140
star
54

remix-workshop

TypeScript
133
star
55

issue-template

A way for github projects to make templates for github issues.
JavaScript
131
star
56

react-hooks-and-suspense-egghead-playlist

This is the code for the egghead playlist "React Hooks and Suspense"
JavaScript
128
star
57

modern-javascript

Get up to speed on the latest, most useful JavaScript features to level up your programming
JavaScript
123
star
58

kcd-discord-bot-v1

The bot for the KCD discord community
TypeScript
123
star
59

app-dev-tools

An example of how to create and hook up App DevTools to improve your development productivity of your application
JavaScript
122
star
60

preval.macro

Pre-evaluate code at build-time with babel-macros
JavaScript
120
star
61

split-guide

A tool to help generate code for workshop repositories
JavaScript
108
star
62

kcd-learning-clubs-ideas

📍 Ideas for curriculum and schedule templates for KCD Learning Clubs
106
star
63

simply-react

JavaScript
104
star
64

nps-utils

Utilities for http://npm.im/nps (npm-package-scripts)
JavaScript
101
star
65

glamorous-website

This is still a work in progress
JavaScript
98
star
66

jest-glamor-react

Jest utilities for Glamor and React
JavaScript
98
star
67

react-hooks-pitfalls

The slides and code examples for my talk "React Hook Pitfalls"
JavaScript
94
star
68

webpack-validator-DEPRECATED

Use this to save yourself some time when working on a webpack configuration.
JavaScript
93
star
69

onewheel-blog

TypeScript
90
star
70

remix-tutorial-walkthrough

I live streamed working through the Remix Jokes App Tutorial
TypeScript
87
star
71

rebase-and-merge

Making this a reality ☞
JavaScript
82
star
72

managing-state-management-slides

79
star
73

css-in-js-precompiler

WORK IN PROGRESS: Precompiles CSS-in-JS objects to CSS strings
JavaScript
72
star
74

create-react-app-react-testing-library-example

JavaScript
67
star
75

10-practical-js-features

JavaScript
67
star
76

rename-gh-to-main

JavaScript
67
star
77

full-stack-components

TypeScript
66
star
78

fakebooks-remix

The Remix version of the fakebooks app demonstrated on https://remix.run. Check out the CRA version: https://github.com/kentcdodds/fakebooks-cra
TypeScript
66
star
79

cypress-testing-workshop

A workshop for learning how to write cypress tests
JavaScript
65
star
80

prettier-eslint-atom

DEPRECATED IN FAVOR OF prettier-atom + ESLint integration
JavaScript
64
star
81

repeat-todo

A simple app I made for my wife
JavaScript
63
star
82

why-react-hooks

Talk about React hooks
JavaScript
62
star
83

codegen.macro

JavaScript
61
star
84

talks

A repo with links to talks that I've given
59
star
85

quick-stack

TypeScript
57
star
86

binode

JavaScript
57
star
87

airtable-netlify-short-urls

There's a simpler version using Netlify redirects instead of Airtable here
JavaScript
57
star
88

fully-typed-web-apps-demo

TypeScript
53
star
89

argv-set-env

Set environment variables in npm scripts
JavaScript
52
star
90

react-test-context-provider

A function that allows you to specify context to pass to a child component (intended for testing only).
JavaScript
48
star
91

concurrent-react

React Suspense Egghead course
JavaScript
47
star
92

incremental-react-router-to-remix-upgrade-path

JavaScript
46
star
93

remix-mdx

JavaScript
45
star
94

setup-prettier

JavaScript
44
star
95

podcastify-dir

Take a directory of audio files and syndicate them with an rss feed
JavaScript
42
star
96

aha-programming-slides

JavaScript
42
star
97

workshop-setup

Verify and setup a repository for workshop attendees
JavaScript
42
star
98

jest-esmodules

JavaScript
40
star
99

typing-for-kids

A little app I made for my kids for Christmas :)
JavaScript
40
star
100

react-suspense-simple-example

JavaScript
39
star