LoginSignup
8
14

More than 5 years have passed since last update.

オブジェクトを収めた配列の値に対してreduceメソッドを適用する

Posted at

reduceメソッドを使った、配列の合計値の求め方。

var array = [1, 10, 100]
array.reduce(function(a, b){ return a + b })
-> 111

配列の内容がオブジェクトで、特定の項目の合計値を求めたい場合は、return でオブジェクトを返す必要がある。

var array = [{value:1},{value:10},{value:100}]

array.reduce(function(a,b){ return a.value + b.value }) //error
-> NaN

array.reduce(function(a,b){ return { value:a.value + b.value } })
-> Object {value: 111}

例)任意の要素の横幅(width値)を取得し、その合計値を返す。

Array.prototype.slice.call(document.querySelectorAll(".testElement"))
    .reduce(function(a,b){
        return { clientWidth:a.clientWidth + b.clientWidth }
    })
-> Object {clientWidth: 1144}
8
14
1

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
8
14