0
1

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.

reduceってめっちゃ便利じゃね?って話

Last updated at Posted at 2023-08-24

概要

JavaScriptの配列操作っていろいろなメソッドありますよね。

  • forEach()
  • map()
  • filter()
  • reduce()

ここら辺が主にあると思うんですが、皆さん何使ってますか?
僕はreduce()を推したい...!!
じゃあ何が嬉しいんだよってことで実際に動かして確認します。

実際にやってみた

先に結論言います。

配列でも、文字列でもなんでも作れます

filterとかmapだと、結果として新しい配列を作ることになります。
reduceだと配列でも、文字列でもなんでも作れます。

以下、サンプル。

まず文字列作る。

文字列作る.js
const tanakaList = ["田中1.男", 
                    "田中2.女",
                    "田中3.男", 
                    "田中4.男", 
  			        "田中5.女",
                    "田中6.男"];

const genderCheck = (list) => {
  return list.reduce((pv, cv) => {
  	const [name, gender] = cv.split('.');
  	gender === "" ? pv += name : '';
    return pv;
  }, "");
};

console.log(genderCheck(tanakaList));
"田中1田中3田中4田中6"

次に配列作る。

配列作る.js
const tanakaList = ["田中1.男", 
                    "田中2.女",
                    "田中3.男", 
                    "田中4.男", 
  			        "田中5.女",
                    "田中6.男"];

const genderCheck = (list) => {
  test = []
  
  list.reduce((pv, cv) => {
  	const [name, gender] = cv.split('.');
  	gender === "" ? test.push(name) : '';
  }, "");

  return test;
};

console.log(genderCheck(tanakaList));
Array ["田中1", "田中3", "田中4", "田中6"]

こんな感じ。

0
1
3

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?