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

mapやfilterを使用した配列の処理

Last updated at Posted at 2021-07-27

##map
繰り返し処理を行うメソッド

#####配列を受け取って、新しい配列を作る

const nameArray = ['ゆう', '吉田', '佐藤']
const nameArray2 = nameArray.map((name) => {
  return name;
})

console.log(nameArray2); // ['ゆう', '吉田', '佐藤']

#####配列を順番に表示する

const nameArray = ['ゆう', '吉田', '佐藤'];

//一行で済む場合はブラケット{}を省略できる。
nameArray.map((name) => console.log(name)); // ゆう, 吉田, 佐藤

#####map関数に順番の概念を持たせる
第二引数を指定することで、インデックス番号を代入できる

nameArray.map((name, index) => console.log(`${index + 1}番目は、${name}です`));

/*1番目は、ゆうです
 *2番目は、吉田です
 *3番目は、佐藤です*/

#####map関数内に条件分岐を実装する

const newNameArray = nameArray.map((name) => {
  if (name === "ゆう") {
    return name
  } else {
    return `${name}さん`
  }
})

console.log(newNameArray);
/*ゆう
 *吉田さん
 *佐藤さん*/

##filter
条件付きの繰り返し処理を行い新しい配列を作るメソッド

//奇数の値のみを取り出して新しい配列を作る
const newNumArray = numArray.filter((num) => {
  return num % 2 === 1;
})

console.log(newNumArray); //[1, 3, 5]
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?