1からNの和を求めます



1からnの整数の和を求めます


index値を追加し続けるだけでいいです.
function solution(n) {
  let answer = 0;
  for (let i = 0; i <= n; i++) {
    answer += i;
  }

  return answer;
}

console.log(solution(30)); // 465

2.すべてのタイル値を追加


Arrayのreduce(Reduser)法を用いてアレイ値の和を容易に求めることができる.
( https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce )
reduce()は配列に存在する各要素に対して1回のコールバック関数を実行し、コールバック関数はアキュムレータ、currentValue、
currentIndex,arrayの4つの引数を受け入れます.
reduce()関数呼び出しがinitialValueを提供する場合、アキュムレータはinitialValueに等しく、currentValueは配列の最初の値に等しい.InitialValueが指定されていない場合、アキュムレータは配列の最初の値に等しく、currentValueは2番目の値に等しい.
let arr = [20, 7, 23, 19, 10, 15, 25, 8, 13];

function sum(arr) {
  let answer = 0; // answer가 initialValue로 제공. 만약 값을 20으로 변경한다면 log에는 160이 찍힘
  answer = arr.reduce((acc, cur) => acc + cur, answer)
  return answer;
}

console.log(sum(arr)) // 140

reduce()の例


1)オブジェクト配列の値のマージ
let init = 0;
let sum = [{age: 10}, {age: 20}, {age: 30}].reduce((acc, cur) => acc + cur.age , init)

console.log(sum) // 60
2)オーバーラップアレイの展開
let flattened = [[0, 1], [2, 3], [4, 5]].reduce((acc, cur) => acc.concat(cur),
  []
);

console.log(flattened) // [0, 1, 2, 3, 4, 5]
3)計算対象内のインスタンス値
let fruits = [
  "Apple",
  "Melon",
  "Apple",
  "Banana",
  "Strawberry",
  "Apple",
  "Banana"
];

let fruitsObj = fruits.reduce((allFruits, fruit) => {
  if (fruit in allFruits) {
    allFruits[fruit]++;
  } else {
    allFruits[fruit] = 1;
  }
  return allFruits;
}, {});

console.log(fruitsObj);
4)属性にグループ化
let people = [
  { name: "Alice", age: 21 },
  { name: "Max", age: 20 },
  { name: "Jane", age: 20 }
];

function groupBy(objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    let key = obj[property];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  }, {});
}

let groupedPeople = groupBy(people, "age");

console.log(groupedPeople);

// {
//  '20': [ { name: 'Max', age: 20 }, { name: 'Jane', age: 20 } ],
//  '21': [ { name: 'Alice', age: 21 } ]
// }
さらなるクリーンアップが必要
Bonding arrays contained in an array of objects using the spread operator and initialValue,
Remove duplicate items in an array,
Replace .filter().map() with .reduce(),
Running Promises in Sequence,
Function composition enabling piping,
reduce等の使用