0
0

More than 3 years have passed since last update.

[filter( ),find( ),findIndex( )]メソッド JavaScript

Last updated at Posted at 2021-09-01

filter( )

filter( )は配列内にある要素が指定された支持にあっていたらそのあっているものだけを配列から取り出して新しい配列の中にいれてくれます。

const characters = ['ab', 'cde', 'fghi', 'jklmn'];
const result = characters.filter(character => character.length > 3); 
console.log(result); => ["fghi", "jklmn"]

上記例だと3文字以上の文字を残し、新しい配列を作ってくれます。

const foods = [
  { name: "pork", type: "meet" },
  { name: "salmon", type: "fish" },
  { name: "beef", type: "meet" },
  { name: "tuna", type: "fish" },
];
const cookingType = materials => {
  if (materials.type === "meet") {
    return true;
  }
  return false;
};
const foodsType = foods.filter(cookingType);
console.log("result\n", foodsType);

.typeがmeetの要素を取り出し、新しい配列を作ってくれます。

find( )

find( )は同じくその支持にあった最初の値を返してくれます。

const array = [2, 10, 55, 180, 23];

const result = array.find(element => element > 8);

console.log(result); => 10

8より大きい数字の最初の10が返ってきました。

findIndex( )

findIndex( )も同じくその支持にあった最初の要素の位置を返してくれて合わなければ−1を返します。

const array = [2, 10, 55, 180, 23];

const number = (element) => element > 20;

console.log(array.findIndex(number)); => 2

配列は0から始まるので20より大きい55の位置の2
が返ってきました。

const array = [2, 10, 55, 180, 23];

const number = (element) => element > 181;

console.log(array.findIndex(number)); => -1

仮に181を比較対象に入れると-1が返ってきました。

0
0
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
0
0