var names = map(customers, getFullName); var nameLengths = map(names, stringLength);
var nameLengths = map(customers, function(customer) { returnstringLength(getFullName(customer)); });
값 하나에 filter() 두번 사용
1 2 3 4 5 6
var goodCustomers = filter(customers, isGoodCustomer); var withAddresses = filter(goodCustomers, hasAddress);
var withAddresses = filter(customers, function(customer) { returnisGoodCustomer(customer) && hasAddress(customer); });
map() 다음에 reduce() 사용하기
1 2 3 4 5 6 7
var purchaseTotals = map(purchases, getPurchaseTotal); var purchaseSum = reduce(purchaseTotals, 0, plus);
var purchaseSum = reduce(purchases, 0, function(total, purchase) { return total + getPurchaseTotal(purchase); });
팁 1: 데이터 만들기
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var answer = []; varwindow = 5;
for(var i = 0; i < array.length; i++) { var sum = 0; var count = 0; for(var w = 0; w < window; w++) { var idx = i + w; if(idx < array.length) { sum += array[idx]; count += 1; } } answer.push(sum/count); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var answer = []; varwindow = 5;
for(var i = 0; i < array.length; i++) { var sum = 0; var count = 0; var subarray = array.slice(i, i + window); for(var w = 0; w < subarray.length; w++) { sum += subarray[w]; count += 1; } answer.push(sum/count); }
팁 2: 한 번에 전체 배열을 조작하기
1 2 3 4 5 6 7 8 9 10 11 12 13
var answer = []; varwindow = 5;
for(var i = 0; i < array.length; i++) { var sum = 0; var count = 0; var subarray = array.slice(i, i + window); for(var w = 0; w < subarray.length; w++) { sum += subarray[w]; count += 1; } answer.push(sum/count); }
1 2 3 4 5 6 7 8
var answer = []; varwindow = 5;
for(var i = 0; i < array.length; i++) { var subarray = array.slice(i, i + window); answer.push(average(subarray)); }
팁 3: 작은 단계로 나누기
1 2 3 4 5 6 7
var answer = []; varwindow = 5;
for(var i = 0; i < array.length; i++) { var subarray = array.slice(i, i + window); answer.push(average(subarray)); }
1 2 3 4 5 6 7 8 9 10 11
var indices = [];
for(var i = 0; i < array.length; i++) indices.push(i);
varwindow = 5; var answer = map(indices, function(i) { var subarray = array.slice(i, i + window); returnaverage(subarray); });