高階関数を使えば配列に対する要素に対しての少し複雑な処理やforループを使って書くような処理もシンプルに書けるようになります。
だけど、代表的な高階関数であるmap
やreduce
がどのような処理ができるか混乱してしまう人も多いと思います。
一目でどの関数で何ができるか図解してみたので、気休めに覗いてみてください!
map
配列のすべての要素に対して関数を適用し、その結果からなる新しい配列を生成します
const people = ['Sad guy', 'Normal guy', 'Exciting guy'];
const mastedPeople = people.map(function(person) {
return person + ' is wearing the mask';
});
console.log(mastedPeople); // ["Sad guy is wearing the mask", "Normal guy is wearing the mask", "Exciting guy is wearing the mask"]
reduce
配列のすべての要素を畳み込んで、1つの値にまとめることができます
const testScores = [40, 70, 90]; // 国語・数学・英語の順番として
const totalScore = testScores.reduce((acc, score) => {
return acc + score;
}, 0);
console.log(totalScore); // 200
filter
配列から特定の条件に合った要素を抽出するために使用します
const movies = [
{ title: "Star Wars", rating: 9.0 },
{ title: "The Avengers", rating: 8.0 },
{ title: "Jurassic Park", rating: 7.5 },
];
const highlyRatedMovies = movies.filter(movie => movie.rating >= 8.5);
console.log(highlyRatedMovies);
/*
output
[{
rating: 9,
title: "Star Wars"
}]
*/
おわりに
よりシンプルにわかりやすいコードを書けるように技術的な勉強をしていきましょう!
参考
# JavaScript Map, Reduce, and Filter - JS Array Functions Explained with Code Examples