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

【初心者向け】Javascriptのfilterとmapメソッドをいい加減マスターする

Last updated at Posted at 2024-04-04

実行環境

簡易的な実行確認はpaiza.ioで行う

おさらい

filter:条件にあう数値の配列になる(値を返すわけではない)

map: 操作した後の配列を返す

まずはfilter

問題:配列に対して、1でない要素のみを返す関数を作る

filterは値を返さない
=> returnする必要がある

const array = [1,2,3,4,5];
const filtered = (array) => return array.filter((n)=> n !==1);

console.log(filtered(array));//[2,3,4,5]

ちなみに以下は誤り

const array = [1,2,3,4,5]

const filtered = array.filter((n)=> n !==1)

console.log(filtered(array))

次にmap

問題:数値の配列に対して、各要素を倍にした数を格納した値を変数に代入する

const array1 = [1, 4, 9, 16];

// Pass a function to map
const map1 = array1.map((x) => x * 2);

console.log(map1); //Array [2, 8, 18, 32]

以下は誤り

const array1 = [1, 4, 9, 16];

const map1 = () => return array1.map((x) => x * 2);

console.log(map1); //Array [2, 8, 18, 32]
0
2
4

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