この記事の最終更新日: 2022年4月10日

検索条件や検索結果の絞り込み(ソート)や並び替えをしたい場面は本当によくあります。
フロントエンドで絞り込み・並び替えを実装しようするととてつもなく面倒なロジックになるのは目に見えています、、、
今回はそんな面倒なロジックとはおさらばできる、「match-sorter」というnpmモジュールを見つけたので、皆さんに共有します。
もちろん、ReactでもVueでもどちらでも利用可能なので安心してください。
インストール
以下のコマンドでインストールできます。
node.js(npm)がインストールされていない場合は、インストール後にこのコマンドを実行してください。
$ npm install match-sorter
使い方
importすることでモジュールを利用できます。
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') // []
matchSorter(絞り込み対象の配列 , 絞り込み用の文字列) で絞り込み&並び替え後の配列が返ってきます。
元々の絞り込み対象の配列には影響はありません。
連想配列のリストも余裕で絞り込めます。
const list = [{name: 'Janice'}, {name: 'Fred'}, {name: 'George'}, {name: 'Jen'}]
matchSorter(list, 'j', {keys: [item => item.name]})
さらに複雑なリストも絞り込み可能です。
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']})
// []
他にもいろんな条件に対応しているので、提供元のGitHubから確認してみてください。
提供元のGitHubはこちら
GitHub - kentcdodds/match-sorter: Simple, expected, and deterministic best-match sorting of an array in JavaScript
Simple, expected, and deterministic best-match sorting of an array in JavaScript - kentcdodds/match-sorter

大阪のエンジニアが書いているブログ。
コメント