2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

配列要素の合計値を出すとき、いろいろとやり方はあるらしいですが、私が最近よく使っているのはreduceです。

これはJavaScriptの関数のひとつで、 配列の全要素を1つの値に畳み込む(reduceする)ために使います。

数値の合計、最大値、オブジェクトへの変換など、汎用的に利用できます。

今回は、reduceの使い方について簡潔にまとめてみました。

reduceの基本構文


const array = [1,2,3,4,5];

console.log(array.reduce((a, b) => a + b, 0));

>>>出力 : 15

reduceの使い方は簡単で、配列名.reduce((変数名1, 変数名2) => 変数名1 + 変数名2, 0))という書き方で合計値を出すことができます。

reduce の第2引数にある「0」は、計算を始めるときの初期値です。
今回の例では合計を出すので、最初の合計値を 0 にしているわけです。
初期値を入れると

  • 配列が空でも安全に計算できる(そのまま 0 が返る)
  • ループの最初から全要素を処理できる

初期値を省略すると、配列の先頭要素が自動的に初期値になります。
この場合、要素が1つ減った状態で計算が始まり、配列が空だとエラーになるため、
合計や積の計算では初期値を明示しておくのが安心です。

使用例

1. 配列の合計を求める

const nums = [1, 2, 3, 4];
const sum = nums.reduce((acc, val) => acc + val, 0);
console.log(sum); // 10

2. 最大値を求める

const nums = [5, 8, 1, 9];
const max = nums.reduce((acc, val) => Math.max(acc, val), -Infinity);
console.log(max); // 9

3. 配列をオブジェクトに変換

const fruits = ['apple', 'banana', 'orange'];
const fruitObj = fruits.reduce((acc, fruit, index) => {
  acc[index] = fruit;
  return acc;
}, {});
console.log(fruitObj); // {0: 'apple', 1: 'banana', 2: 'orange'}

4. ネスト配列の平坦化

const nested = [[1, 2], [3, 4], [5]];
const flat = nested.reduce((acc, val) => acc.concat(val), []);
console.log(flat); // [1, 2, 3, 4, 5]
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?