.reduce() method
reduce() methodを使うことで、arrayの要素から1つの値を計算します。
reduce() method reduces an array into a single value.
よく使われるのは、足し算と掛け算です。
const grades = [10, 15, 5];
const sum = grades.reduce((total, current) => {
return total + current
}, 0);
total変数は0から始まり、そのあと繰り返しの中でtotalの値がアップデートされていきます、total + currentが行われます
上の例では、totalは0から始まり、10, 25, 最終的に30となります
Reducing array of objects
const grades = [{grade: 10}, {grade: 15}, {grade: 5}];
というarray of objectsを前提にすると
const sum = grades.reduce((total, current) => {
return total + current.grade;
}, 0);
30が返ってきます
ここでcurrentにはオブジェクトが入ってくるので、数値を取るにはcurrent.gradeを入力する必要があります
もう1つ例をあげます
次のarray of objectsを前提として、”social impact”を”likes” + “retweets”で計算するとします
const tweets = [
{
id: 10512,
stats: {
likes: 41,
retweets: 54
}
},
{
id: 41241,
stats: {
likes: 14,
retweets: 20
}
}
];
const socialImpact = tweets.reduce((total, current) => {
console.log(current); // you can also call it tweet. Visualize the object
return total + current.stats.likes + current.stats.retweets;
}, 0);
console.log(socialImpact); // 129
コメントを書く