find


ArrayはArray Classの例です.したがって,Array Classで定義した手法を利用することができる.主人はArrayの助けでOOPとFRPの基礎を学びたいと思っています.

find

let heroes = [
    { id: 1, name: 'superman', type: 'Flying', cost: 400 },
    { id: 2, name: 'batman', type: 'Flying', cost: 320 },
    { id: 3, name: 'X-man', type: 'Mutant', cost: 200 },
    { id: 4, name: 'Ironman', type: 'Metal', cost: 530 },
    { id: 5, name: 'Antman', type: 'Insect', cost: 180 },
];
上のhereosからbatmanの情報を取得したい場合はfindメソッドを使用します.
let foundHero = heroes.find(function (hero) {
    return hero.name === 'batman';
});
console.log(foundHero);
興味深いことに、filterと何が違うのか.違いは、例えばバットマンがもう一人います.2番目のバットマンのIDは11です
次に、filterは配列にすべての要素を含みます.数え切れないほど返す.
let filter = heroes.filter(function (hero) {
    return hero.name === 'batman';
});
console.log(filter);
//[{ id: 2, name: 'batman', type: 'Flying', cost: 320 },
// { id: 11, name: 'batman', type: 'Flying', cost: 320 }]
これとは異なり、findはarrayに置かず、object形式の1つの要素のみを抽出し、条件を満たす様々なものがあれば、その中の一番前のものだけを取り戻す.これがfilterとfindの違いです.
let foundHero = heroes.find(function (hero) {
    return hero.name === 'batman';
});
console.log(foundHero);
// { id: 2, name: 'batman', type: 'Flying', cost: 320 }

find練習


1.最初の練習問題
findを利用して練習する前にfilter練習問題でやったこと.
filter練習問題は以下の通りです.
function commentPerWriter(comments, name) {
    function searchId(heroes, name) {
        return heroes.filter(function (hero) {
            return hero.name === name;
        });
    }
    let searchedHero = searchId(heroes, name);

    let sorted = comments.filter(comment => comment.idOfWriter === searchedHero[0].id);
    return sorted;
}

console.log(commentPerWriter(comments, 'superman'));
findを使用して値を取得するには、次の手順に従います.
function commentPerWriter(comments, name) {
    function searchId(heroes, name) {
        return heroes.find(function (hero) {
            return hero.name === name;
        });
    }
    let searchedHero = searchId(heroes, name);

    let sorted = comments.filter(comment => comment.idOfWriter === searchedHero.id);
    return sorted;
}

console.log(commentPerWriter(comments, 'superman'));
2.2番目の練習問題
誰がadmin権限を持っているか探します.
// 1. Find the user in the users's array who is an admin
let users = [
    { id: 1, admin: false },
    { id: 2, admin: true },
    { id: 3, admin: false },
];

let admin;
ソースコード
let admin = users.find(function (user) {
    return user.admin === true;
});
console.log(admin);
3.3番目の練習問題
// 2. Find the account with a balance of more than 200
function findWhere(array, criteria) {}

// for example
let ladders = [
    { id: 1, height: 20 },
    { id: 2, height: 25 },
];

findWhere(ladders, { height: 24 }); // result: {id:2, height:25}
ソースコード
function findWhere(array, criteria) {
    let { height } = criteria;
    return array.find(function (el) {
        return el.height === height;
    });
}