3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[JavaScript] filter() メソッドは超便利。

Posted at

filter() メソッドとは

filter()メソッド は、引数として与えられたテスト関数を各配列要素に対して実行し、それに合格したすべての配列要素からなる新しい配列を生成する。

つまり、、イミュータブルに配列を操作することができる。

例1
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6); // 6文字より大きい要素だけを取り出し、新しい配列に格納する。
console.log(result); => ["exuberant", "destruction", "present"]
例2
const arr = [
  { id: 0, name: "fdoif", hobby: "soccer" },
  { id: 1, name: "hohfd", hobby: "baseball" },
  { id: 2, name: "fhofi", hobby: "bascketball" },
  { id: 3, name: "fefef", hobby: "soccer" },
  { id: 4, name: "sassa", hobby: "baseball" }
];

const filterByHobby = item => {
  if (item.hobby === "soccer") {
    return true;
  }

  return false;
};

const arrByHobby = arr.filter(filterByHobby); //hobbyがsoccerの要素だけを取り出し、新しい配列に格納する。

console.log("Filtered Array\n", arrByHobby);

超便利!!!

以上です。

参考: Array.prototype.filter() | MDN

3
2
0

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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?