Vanilla JS と Lodash で連想配列を累計する
1. はじめに
本記事では,JavaScript を用いて以下ような連想配列を累計する方法について考えます。様々な実装方法が考えられますが,本記事では Vanilla JS を用いた方法とユーティリティライブラリである Lodash を用いた方法について記述します。
1# 処理前2
3[4 { date: '2020-01-01', sales: 100 },5 { date: '2020-01-02', sales: 200 },6 { date: '2020-01-03', sales: 300 },7]8
9# 処理後10
11[12 { date: '2020-01-01', sales: 100, accumulation: 100 },13 { date: '2020-01-02', sales: 200, accumulation: 300 },14 { date: '2020-01-03', sales: 300, accumulation: 600 }15]
本記事内で行っている作業は以下の環境下で実行したものです。また,Node.js や Lodash はインストール済みの前提で記述しており,インストール手順は割愛していることをご了承ください。
- Lodash Ver.4.17.20
- Node.js Ver.12.18.3
- Zorin OS 15.2 Core (Ubuntu 18.04 LTS)
2. Vanilla JS
様々な実装が考えられますが,今回はインターネットで公開されている記事を参考に,reduce を用いることで累計を実装しています。
1const before = [2 { date: '2020-01-01', sales: 100 },3 { date: '2020-01-02', sales: 200 },4 { date: '2020-01-03', sales: 300 },5]6
7const after = before.reduce((acc, cur, idx) => {8 if (acc.length) {9 cur.accumulation = cur.sales + acc[idx - 1].accumulation10 } else {11 cur.accumulation = cur.sales12 }13 acc.push(cur)14 return acc15}, [])16
17console.log(after)
上記のソースコードを app.js というファイル名で任意のフォルダ内に保存します。app.js を実行すると,正常に累計されていることが確認できました。
1$ node app.js2[3 { date: '2020-01-01', sales: 100, accumulation: 100 },4 { date: '2020-01-02', sales: 200, accumulation: 300 },5 { date: '2020-01-03', sales: 300, accumulation: 600 }6]
3. Lodash
こちらも Vanilla JS 同様に様々な実装が考えられますが,今回は Lodash が提供している reduce を用いて実装しています。
1const _ = require('lodash')2
3const before = [4 { date: '2020-01-01', sales: 100 },5 { date: '2020-01-02', sales: 200 },6 { date: '2020-01-03', sales: 300 },7]8
9const after = _(before).reduce((acc, cur, idx) => {10 if (acc.length) {11 cur.accumulation = cur.sales + acc[idx - 1].accumulation12 } else {13 cur.accumulation = cur.sales14 }15 acc.push(cur)16 return acc17}, [])18
19console.log(after)
上記のソースコードを app.js というファイル名で任意のフォルダ内に保存します。app.js を実行すると,正常に累計されていることが確認できました。
1$ node app.js2[3 { date: '2020-01-01', sales: 100, accumulation: 100 },4 { date: '2020-01-02', sales: 200, accumulation: 300 },5 { date: '2020-01-03', sales: 300, accumulation: 600 }6]
4. おわりに
ここまで,Vanilla JS と Lodash を用いて連想配列を累計する方法について記述してきました。Vanilla JS の reduce と Lodash の reduce に大きな差がないため,ほとんど同じソースコードになりました。今回は実行速度を計測していないため,パフォーマンスの観点から比較することが出来ていません。