1
2

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 3 years have passed since last update.

mapやら、filterやら、reduceやらややこしいぜ!!

Last updated at Posted at 2021-07-06

初学者のJSメモ、、

javascriptでよく見る map,filter,reduce関数。
これらはリスト反復処理をしてくれるライブラリ関数である。

map

通常の書き方であれば、

const array1 = [1,2,3]
const array2 = array.map(x=>2*x)
console.log(array2)[2,4,6]

ラムダ関数Ver

function realMap(f,list) {
 let answer = [];
   for(let i = 0; i < list.length; i++) answer.push(f(list[i]));
   return answer;
}
console.log(realMap(function(){x=>x*2},array1)[2,4,6]

こんな感じです。

filter

通常の書き方

let list1 = [1,2,3,4,5,6,7,8,9,10]
console.log(list1.filter(x=>x%2!==0));[2,4,6,8,10]

ラムダ関数Ver

function realFilter(f, list){
   let answer = [];
   for(let i = 0; i < list.length; i++){
       if(f(list[i]) === true) answer.push(list[i]);
   }
   return answer;
}
 
console.log(realFilter(x=>x%2!==0, list1));[2,4,6,8,10]

reduce

通常Ver

let list1 = [1,2,3];
console.log(list1.reduce((total,x)=>total*x));→6

ラムダVer

function realReduce(callback, list, start){
  let answer = start;
  for(let i = 0; i < list.length; i++){
      let result = callback(list[i], answer);
      answer = result;
  }
  return answer;
}
console.log(realReduce((x,total)=>x*total, list1, 1));

前回の記事と合わせれば理解が深まるはず、、、

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?