0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScript 配列 reduce()関数:配列を一つの結果値にまとめる

0
Posted at

😄この投稿は、codingeverybody.jpのコンテンツをもとに作成しています。

定義と使い方

配列において reduce() 関数は、配列を巡回しながらコールバック関数を使用して、配列を一つの値へと反復的に減らし(reduce)、単一の値として返します。

特徴

  • 配列の要素を巡回し、一つの値へと減らしていくロジックをコールバック関数に記述します。
  • 各段階で減らした値は return キーワードで返されます。
  • 返された値は次の巡回で累積値として使用され、同じロジックで減らし続けます。
  • 元の配列はそのまま維持され、最終的に反復して減らした単一の値が返されます。

基本例

/**
 * reduce() 関数を使用して
 * 配列の全要素を足し合わせ、累計された一つの値を生成する例
 */

// reduce() 関数を適用する配列
const numbers = [1, 2, 3, 4, 5];

// 開発者が直接作成したコールバック関数
function sum(total, number) {
    // 以前の結果値と現在の要素を足します。
    return total + number;
}

// 配列の全要素にコールバック関数を適用し、集計した一つの結果値を返す
const result = numbers.reduce(sum);
console.log(result); // 出力: 15

構文

arr.reduce(callbackFn[, initialValue])

活用例

# 配列のすべての要素を加算する

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

const sum = (total, number) => {
	return total + number;
}

const result = numbers.reduce(sum);
console.log(result); // 出力: 15

# 配列のすべての要素を乗算する

const numbers = [2, 3, 4, 5];

const sum = (total, number) => {
	return total * number;
}

const result = numbers.reduce(sum, 1);
console.log(result); // 出力: 120

# 配列の最小値を見つける

const numbers = [5, 3, 9, 2, 7];

const min = (min, item) => {
    return (item < min) ? item : min;
}

const result = numbers.reduce(min, numbers[0]);
console.log(result); // 出力: 2

# 配列の最大値を見つける

const numbers = [5, 3, 9, 2, 7];

const max = (max, item) => {
    return (item > max) ? item : max;
}

const result = numbers.reduce(max, numbers[0]);
console.log(result); // 出力: 9

# 配列を返す方法

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

const square = (accumulator, currentValue) => {
    // 現在の要素の二乗値を計算して配列に追加
    accumulator.push(currentValue * currentValue);
    return accumulator; // 累積された配列を返却
}

const squaredArray = numbers.reduce(square, []);

console.log(squaredArray); // 出力: [1, 4, 9, 16, 25]

参考資料

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?