LoginSignup
0
1

More than 1 year has passed since last update.

代表的な高階関数を図解してみた

Last updated at Posted at 2023-02-05

高階関数を使えば配列に対する要素に対しての少し複雑な処理やforループを使って書くような処理もシンプルに書けるようになります。
だけど、代表的な高階関数であるmapreduceがどのような処理ができるか混乱してしまう人も多いと思います。
一目でどの関数で何ができるか図解してみたので、気休めに覗いてみてください!


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"]

Screen Shot 2023-02-05 at 14.25.35.png

reduce

配列のすべての要素を畳み込んで、1つの値にまとめることができます

const testScores = [40, 70, 90]; // 国語・数学・英語の順番として

const totalScore = testScores.reduce((acc, score) => {
  return acc + score;
}, 0);

console.log(totalScore); // 200

Screen Shot 2023-02-05 at 14.26.21.png

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"
	}] 
  */

Screen Shot 2023-02-05 at 14.38.09.png

おわりに

よりシンプルにわかりやすいコードを書けるように技術的な勉強をしていきましょう!

参考

# JavaScript Map, Reduce, and Filter - JS Array Functions Explained with Code Examples

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