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?

More than 1 year has passed since last update.

qittaの記事を見てぱっと見謎だったfilter, reduceに渡すアロー関数を理解した

Last updated at Posted at 2022-01-10

qittaの記事を見てぱっと見謎だったソースが以下。

index.ts
function sumOfPos(arr: number[]): number {
  return arr.filter(num => num >= 0).reduce((acc, num) => acc + num, 0);
}

まず以下の部分

index.js
arr.filter(num => num >= 0)

javascriptのfilter関数の公式を見てみると

index.js
let newArray = arr.filter(callback(element[, index, [array]])[, thisArg])

そうかfilter関数の引数にコールバック関数を渡すのか。
とすると無名関数を渡しているので以下と同義。

index.js
arr.filter(function(num){
   return num >= 0;
});

続いて以下の部分

index.js
reduce((acc, num) => acc + num, 0)

これもjavascriptのreduce関数の公式をみると
第一引数にコールバック関数を渡すみたい。なので、
(第2引数は初期値)

index.js
reduce(function(acc, num){
 return acc + num;
}, 0);

つまり

index.ts
const data: number[] = [-1, 5, -3, 4, -2, 5];
function sumOfPos(arr: number[]): number {
    return arr.filter(num => num >= 0).reduce((acc, num) => acc + num, 0);
}
console.log(sumOfPos(data));  //5 + 4 + 5 = 14
0
0
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
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?