682 words
3 minutes
Vanilla JS と Lodash で連想配列を累計する
2020-12-05
2020-12-15
1. はじめに
本記事では,JavaScript を用いて以下ような連想配列を累計する方法について考えます。様々な実装方法が考えられますが,本記事では Vanilla JS を用いた方法とユーティリティライブラリである Lodash を用いた方法について記述します。
# 処理前
[ { date: '2020-01-01', sales: 100 }, { date: '2020-01-02', sales: 200 }, { date: '2020-01-03', sales: 300 },]
# 処理後
[ { date: '2020-01-01', sales: 100, accumulation: 100 }, { date: '2020-01-02', sales: 200, accumulation: 300 }, { date: '2020-01-03', sales: 300, accumulation: 600 }]
本記事内で行っている作業は以下の環境下で実行したものです。また,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 を用いることで累計を実装しています。
const before = [ { date: '2020-01-01', sales: 100 }, { date: '2020-01-02', sales: 200 }, { date: '2020-01-03', sales: 300 },]
const after = before.reduce((acc, cur, idx) => { if (acc.length) { cur.accumulation = cur.sales + acc[idx - 1].accumulation } else { cur.accumulation = cur.sales } acc.push(cur) return acc}, [])
console.log(after)
上記のソースコードを app.js というファイル名で任意のフォルダ内に保存します。app.js を実行すると,正常に累計されていることが確認できました。
$ node app.js[ { date: '2020-01-01', sales: 100, accumulation: 100 }, { date: '2020-01-02', sales: 200, accumulation: 300 }, { date: '2020-01-03', sales: 300, accumulation: 600 }]
3. Lodash
こちらも Vanilla JS 同様に様々な実装が考えられますが,今回は Lodash が提供している reduce を用いて実装しています。
const _ = require('lodash')
const before = [ { date: '2020-01-01', sales: 100 }, { date: '2020-01-02', sales: 200 }, { date: '2020-01-03', sales: 300 },]
const after = _(before).reduce((acc, cur, idx) => { if (acc.length) { cur.accumulation = cur.sales + acc[idx - 1].accumulation } else { cur.accumulation = cur.sales } acc.push(cur) return acc}, [])
console.log(after)
上記のソースコードを app.js というファイル名で任意のフォルダ内に保存します。app.js を実行すると,正常に累計されていることが確認できました。
$ node app.js[ { date: '2020-01-01', sales: 100, accumulation: 100 }, { date: '2020-01-02', sales: 200, accumulation: 300 }, { date: '2020-01-03', sales: 300, accumulation: 600 }]
4. おわりに
ここまで,Vanilla JS と Lodash を用いて連想配列を累計する方法について記述してきました。Vanilla JS の reduce と Lodash の reduce に大きな差がないため,ほとんど同じソースコードになりました。今回は実行速度を計測していないため,パフォーマンスの観点から比較することが出来ていません。