LoginSignup
2
2

More than 3 years have passed since last update.

JavaScript で配列要素の特定プロパティの値を map と reduce で連結する

Posted at

サンプルコード

// データ
const arr = [
  {foo: 'hello',   bar:   1},
  {foo: 'world',   bar:  20},
  {foo: 'goodbye', bar: 300}
]

// foo の文字列をつなげる
const foo_list = arr.map(x => x.foo).reduce((acc, cur) => acc + ', ' + cur)
console.log(`foo_list = ${foo_list}`)

// bar の値を足す
const bar_total = arr.map(x => x.bar).reduce((acc, cur) => acc + cur)
console.log(`bar_total = ${bar_total}`)

実行結果の例 (Node.js v14.15.1 を使用)。

foo_list = hello, world, goodbye
bar_total = 321

参考資料

Array.prototype.map() - JavaScript | MDN

map() メソッドは、与えられた関数を配列のすべての要素に対して呼び出し、その結果からなる新しい配列を生成します。

Array.prototype.reduce() - JavaScript | MDN

reduce() メソッドは、配列の各要素に対して (引数で与えられた) reducer 関数を実行して、単一の出力値を生成します。

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