LoginSignup
1
0

More than 5 years have passed since last update.

TypeScript(ES)でオブジェクトの配列をAND検索で絞り込み

Last updated at Posted at 2019-01-28

TypeScriptでオブジェクトの複数格納された配列から文字列検索をする

Itemの型(一例)

class Item {
  public id!: number;
  public name!: string;
  public subtitle!: string;
}

Itemの配列から、nameとsubtitleで検索をしてItemの配列を返す関数

// Item型の配列と検索ワードを受け取りItem型の配列を返す関数
function getSearchedItems(items: Item[], keyword: string): Item[] {
// filterで条件に合う物だけを返す配列に入れていく
  const searchedItems = items.filter(item => {
    const keywords: string[] = keyword.split(/[  ]/g); //半角スペースと全角スペースで切り分ける
    const searched =
      (item.name ? item.name : "") + (item.subtitle ? item.subtitle : "");//検索されるワードをくっつける
//検索ワードごとに文字列内に見つかるかを確認し、全てのワードが見つかればtrueを返す(Filter済みの配列に追加される)
    return keywords.every(keyword => {
      return searched.search(keywords[0]) > -1;
    });
  });
  return searchedItems;
}

実際に検索をしてみる例

class Item {
  public id!: number;
  public name!: string;
  public subtitle!: string;
}

function getSearchedItems(items: Item[], keyword: string): Item[] {
  const searchedItems = items.filter(item => {
    const keywords: string[] = keyword.split(/[  ]/g); //半角スペースと全角スペースで切り分ける
    const searched =
      (item.name ? item.name : "") + (item.subtitle ? item.subtitle : "");
    return keywords.every(keyword => {
      return searched.search(keywords[0]) > -1;
    });
  });
  return searchedItems;
}
// 検索する配列
const items: Item[] = [
  {
    id: 1,
    name: "Kingdom hearts",
    subtitle: "大好評発売中"
  },
  {
    id: 2,
    name: "Acecombat",
    subtitle: "Steam版もうすぐ発売"
  },
  {
    id: 3,
    name: "League of Legends",
    subtitle: "Season 9 start"
  },
];
// 検索して結果を表示
console.log(getSearchedItems(items, "Steam Ace"));

あまり調べずにこうなってしまったのでベストプラクティスがあれば教えてください。
→頂いていたご指摘修正しました。

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0