問題一覧に戻る
中級array-methods
問題56: findIndex メソッド

findIndexメソッドを使って条件に合う最初の要素のインデックスを取得する方法を学びましょう。findが要素そのものを返すのに対し、findIndexはその要素の位置(インデックス)を返します。要素の位置が必要な場合、例えば配列から要素を削除したり、置き換えたりする場合に便利です。indexOfと違い、複雑な条件で検索できる点が特徴です。

// findIndexメソッド
const scores = [65, 78, 92, 54, 88, 71];

// 70点以上の最初のインデックスを見つける
const firstPassingIndex = scores.(function(score) {
return score 70;
});

console.log("最初の合格点のインデックス: " + firstPassingIndex);

// プロパティで検索
const products = [
{ id: 101, name: "ノートパソコン", price: 100000 },
{ id: 102, name: "マウス", price: 3000 },
{ id: 103, name: "キーボード", price: 8000 }
];

const targetId = 102;
const productIndex = products.(function(product) {
return product.id targetId;
});

console.log("ID 102の商品のインデックス: " + productIndex);