LoginSignup
1
2

More than 1 year has passed since last update.

reduceの使い方まとめ(Javascript、配列の合計など)

Last updated at Posted at 2022-06-15

はじめに

reduce()関数の使い方をまとめたいなと思い作成しました。

引数

引数 callbackFn initialValue

callbackFn
4 つの引数を取る「縮小」関数になります。

引数 previousValue currentValue currentIndex array

  • previousValue
    配列の値を格納できたりして(大体何でも入る)、ループ終了後にpreviousValueの結果を返却します。初期値はinitialValueで設定できます。
    設定しない場合はarray[0]番目が初期値になります。

  • currentValue
    array[0]またはarray[1]からarray[array.length - 1](配列末尾)まで値を呼び出します。
    初回の呼び出しでは initalValueが指定された場合は array[0] の値であり、そうでない場合は array[1] の値です。

  • currentIndex
    配列の添え字番号です。配列末尾までインクリメントします。
    こちらも初回の呼び出しではinitalValueが指定された場合は 0 の値であり、そうでない場合は 1 の値です。

  • array
    array.reducearrayですね。ドキュメントいわく 走査する配列です

initialValue

previousValueの初期値です。

※指定しないと配列の添え字番号1の値から繰り返し処理が始まるので注意です。

合計のまとめ

配列の数字
sum.jsx
// リストの作成
const listNumber = [1,2,3,4,5];
//合計
const hoge = listNumber.reduce((sum, item) => (sum += item), 0);
console.log(hoge); //15

配列の文字列

sum.jsx
// リストの作成
const listStr = ["H","E","L","L","O"];

//合計
const hoge = listStr.reduce((sum, item) => (sum += item), "");
console.log(hoge); //HELLO

配列から配列

sum.jsx
// リストの作成
const list = [
    [1, 2, 3],
    [1, 2, 3],
  ];

//合計
const hoge = list.reduce(
    (sum, item) => (sum += item.reduce((minSum, elm) => (minSum += elm), 0)),
    0
  );
console.log(hoge); //12

配列からオブジェクト

sum.jsx
// リストの作成
const list = [{ age: 10 }, { age: 10 }, { age: 10 }, { age: 10 }, { age: 10 }];

//合計
const hoge = list.reduce((sum, item) => (sum += item.age), 0);
console.log(hoge); //50

オブジェクト

sum.jsx
// オブジェクトの作成
const obj = {key1: 1, key2: 2, key3: 3}

//合計
const hoge = Object.values(obj).reduce((sum, item) => (sum += item), 0);
console.log(hoge); //6

オブジェクトから配列

sum.jsx
// オブジェクトの作成
const obj = {
    key1: [1, 2, 3],
    key2: [4, 5, 6],
  };

//合計
const hoge = Object.values(obj).reduce(
    (sum, item) => (sum += item.reduce((sumMin, elm) => (sumMin += elm), 0)),
    0
  );
console.log(hoge); //21

オブジェクトからオブジェクト

sum.jsx
// オブジェクトの作成
const obj = {
    key1: { x: 1, y: 2 },
    key2: { x: 3, y: 4 },
  };

//合計
const hoge = Object.values(obj).reduce(
    (sum, item) => (sum += Object.values(item).reduce((sumMin, elm) => (sumMin += elm), 0)),
    0
  );
console.log(hoge); //10

オブジェクトからオブジェクトで特定のプロパティだけ合計

sum.jsx
// オブジェクトの作成
const obj = {
    key1: { x: 1, age: 2 },
    key2: { x: 3, age: 4 },
  };

//合計
const hoge = Object.values(obj).reduce((sum, item) => (sum += item.age), 0);
console.log(hoge); //6

その他操作

二次元配列を一次元配列にする
lest.jsx
// リストの作成
const list = [
    [0, 1],
    [2, 3],
    [4, 5],
  ];
//配列を一次元配列に変更
const hoge = list.reduce((coalescence, item) => coalescence.concat(item), []);
  
console.log(hoge); //(6) [0, 1, 2, 3, 4, 5]

同じ名前の数をかぞえ、オブジェクト型で出力

obj.jsx
// リストの作成
const list =  ["Alice", "Bob", "Bob", "Tiff", "Bruce", "Alice"];
//名前の数をかぞえ、オブジェクト型で出力
const hoge = list.reduce((allNames, name) => {
    if (name in allNames) {
      allNames[name]++;
    } else {
      allNames[name] = 1;
    }
    return allNames;
  }, {});
  
console.log(hoge); //{Alice: 2, Bob: 2, Tiff: 1, Bruce: 1}

オブジェクトに含まれてる配列を一つの配列にする

lest.jsx
// リストの作成
const list =  {
      name: "Anna",
      books: ["Bible", "Harry Potter"],
      age: 20,
    },
    {
      name: "Bob",
      books: ["War and peace", "Romeo and Juliet"],
      age: 29,
    },
    {
      name: "Alice",
      books: ["The Lord of the Rings", "The Shining"],
      age: 17,
    },
  ];

//一次元配列で出力
const hoge = list.reduce((allBooks, currentBook) => [...allBooks, ...currentBook.books], []);
  
console.log(hoge); //(6) ['Bible', 'Harry Potter', 'War and peace', 'Romeo and Juliet', 'The Lord of the Rings', 'The Shining']

配列内の重複要素を除去する

lest.jsx
// リストの作成
const list = ["a", "b", "a", "b", "c", "e", "e", "c", "d", "d", "d", "d", "f"];

//重複削除
const hoge = list.reduce((onl, num) => {
    if (onl.indexOf(num) === -1) {
      onl.push(num);
    }
    return onl;
  }, []);
  
console.log(hoge); //(6) ['a', 'b', 'c', 'e', 'd', 'f']

//関係はないけどこっちのが楽に書ける
const hoge2 = Array.from(new Set(list));
console.log(hoge2); //(6) ['a', 'b', 'c', 'e', 'd', 'f']

まとめ

まだまだ使い方ありそうですが、一旦はこれで完了とします。
1
2
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
1
2