let users = [
{name: 'Tim', age: 40},
{name: 'Satya', age: 30},
{name: 'Sundar', age: 50},
]
=> undefined
function makeAddressBook(addressBook, user){
// 이름의 첫번째 글자로, key를 만든다.
let firstLetter = user.name[0];
// addressBook은 객체다.
// addressBook { }
if(firstLetter in addressBook){
// 만일, key가 있으면, 해당배열에, 사람을 추가한다.
addressBook[firstLetter].push(user);
}else{
// 만일, key가 없으면, 해당 배열을 만들고, 사람을 추가한다.
addressBook[firstLetter] = [];
addressBook[firstLetter].push(user);
}
return addressBook;
}
users.reduce(addressBook, { });
==> addressBook (accumulator)
==> { } 객체 초기값
ex)
const array1 = [1, 2, 3, 4];
// 1 + 2 + 3 + 4 = 10;
console.log(array1.reduce(reducer));
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
'TIL > JavaScript' 카테고리의 다른 글
THIS, 5 patterns of Binding(window(parent), constructor, apply, call (0) | 2020.02.23 |
---|---|
Object.keys( ) (0) | 2020.01.08 |
push() (0) | 2020.01.08 |
push() (0) | 2020.01.08 |
split('') && Array.from && [...] (0) | 2020.01.08 |
comment