[ 2, 5, 9 ].reduce((sum /** сумма **/, current_number /** текущее число **/) => {
sum = sum + current_number;
return sum;
}, 0 /** начальное значение для суммы **/)
// сумма равна 16
const employees = [
{
name: 'Vasiliy',
age: 29,
salary: 50000
},
{
name: 'Ben',
age: 42,
salary: 76000
},
{
name: 'Emma',
age: 19,
salary: 120000
}
];
const employees_data = employees.reduce((data /** данные по сотрудникам **/, employee /** сотрудник **/) => {
data.total_age = data.total_age + employee.age;
data.total_salary = data.total_salary + employee.salary;
return data;
}, { total_age: 0, total_salary: 0 } /** начальное значение **/)
console.log(`Средний возраст сотрудника: ${ employees_data.total_age / employees.length },\nсредняя зп: ${ employees_data.total_salary / employees.length }`)
var options = 'a.b.c.d';
var parts = options.split('.'); // [ 'a', 'b', 'c', 'd' ]
var obj = {};
var result;
parts.reduce((current_object, part) => {
current_object[part] = {};
return current_object[part]
}, obj);
// #1: current_object = {} (просто obj), part = 'a', (obj = {})
// current_object['a'] = {}
// return current_object['a']
// #2: current_object = {} (obj.a), part = 'b', (obj = { a: {} })
// current_object['b'] = {}
// return current_object['b']
// #3: current_object = {} (obj.a.b), part = 'c', (obj = { a: { b: {} } })
// current_object['c'] = {}
// return current_object['c']
// #4: current_object = {} (obj.a.b.c), part = 'd', (obj = { a: { b: { c: {} } } })
// current_object['d'] = {}
// return current_object['d']
// obj = { a: { b: { c: { d: {} } } } }