0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TypeScriptで配列要素のパラメータの総和を出す

Posted at

Qiita内にありそうでなかったっぽいので、備忘録も兼ねて書いておきます。

function sumOf<T>(arr: Array<T>, f: (el: T) => number): number {
    return arr.reduce<number>(
        (sum: number, el: T) => sum + f(el),
        0
    );
}

// 数値配列ならば恒等関数と一緒に渡せば総和が出ます
sumOf([1, 2, 3, 4], el => el)

// 数値ではないものの配列でも、それから数値を返させる関数があれば総和が出せます
sumOf([{a: 1, b: 'hoge'}, {a: 3, b: 'fuga'}], el => el.a)

// 配列要素から数値が出てくれば、総和を取る対象の出し方は何だって良いです
sumOf(
    [{expect: 100, actual: 90}, {expect: 100, actual: 110}],
    el => (el.actual - el.expect) * (el.actual - el.expect) / el.expect
);

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?