reduce Array.prototype.reduce()では配列から最終的にひとつの値を得ることができます。
var members = [
{
name: 'Yamada Takami',
age: 35
},
{
name: 'Yamada Yukihisa',
age: 30
},
{
name: 'Oyamada Akihiro',
age: 34
}
];
var average = members.reduce(function (acc, object) {
return acc + object.age
}, 0) / members.length;
console.log(average);
// 33
var data = [
{
name: 'Yamada Takami',
twitter: 'tacamy'
},
{
name: 'Yamada Yukihisa',
twitter: 'ykhs'
}
];
var users = {};
var users = data.reduce(function (acc, object) {
acc[object.twitter] = object.name;
// key value
return acc;
}, {});
console.log(users);
// {tacamy: "Yamada Takami", ykhs: "Yamada Yukihisa"}
var array = [1, 3, 5, 7];
var result = array.reduce(function (previous, current) {
console.log('previous: ' + previous + ' current: ' + current);
return previous + current;
}, 10); // 初期値に10を設定
console.log('result: ' + result);
// previous: 10 current: 1
// previous: 11 current: 3
// previous: 14 current: 5
// previous: 19 current: 7
// result: 26
var data = [5,6,7,8];
var result = data.reduce(function(a,b){
return a + b;
});
console.log(result);//26
// 2つの値の合計値を求める関数
function add(a, b) {
return a + b;
}
var array = [1, 3, 5, 7];
var result = array.reduce(add);
console.log(result);
// 16