Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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}
_shimizu
群馬・東京間を行き来する出稼ぎエンジニアです。ブログではGIS(地理情報システム)・データビジュアライゼーション・オープンデータなどについて書いてます。JavaScript勉強中
http://shimz.me/blog/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした