LoginSignup
0
0

More than 5 years have passed since last update.

freecodecampのWrite Higher Order Arrow Functionsを解いたメモ

Posted at

 実際の問題へのリンク

 問題概要

与えられた配列から正の整数を取り出し、取り出された正の整数で自乗された(squared)配列を新たに作成する。

 自分の回答

javascript
 const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
 const squareList = (arr) => {
   "use strict";
   // change code below this line
   const squaredIntegers = arr.filter((num) => num > 0 && Number.isInteger(num) ).map(filteredNum => filteredNum ** 2);
   // change code above this line
   return squaredIntegers;
 };
 // test your code
 const squaredIntegers = squareList(realNumberArray);
 console.log(squaredIntegers);

 解説

引数arrが与えられた配列で、まずこの配列からfilter()を使用し正の整数を取り出す。
numに配列の各値が入る。このときnumの変数名は自由につけてOK。
Number.isInteger(値) で整数を取り出す。
整数には負の数も含まれるため 値 > 0 で正の整数に絞り込む。

javascript
 const squaredIntegers = arr.filter((num) => num > 0 && Number.isInteger(num) );

ここまでで正の整数は取り出せた。
次は取り出した値で自乗を行いつつ、その結果を配列として生成する。
map()を使用して新たな配列を生成。
filteredNumに配列の各値が入ってくる。
「なにかしらの処理」の部分に今回でいうと自乗を行うコードを書く。

javascript
 const squaredIntegers = arr.map(filteredNum => なにかしらの処理);

べき乗の計算は ** を使う。 (Math.pow() もOK)
今回の問題では、取り出した値の2乗を行えばOK。

javascript
 const squaredIntegers = arr.map(filteredNum => filteredNum ** 2);

const squaredIntegers = arr.filter((num) => num > 0 && Number.isInteger(num) );

const squaredIntegers = arr.map(filteredNum => filteredNum ** 2);
をがっちゃんこ。

javascript
 const squaredIntegers = arr.filter((num) => num > 0 && Number.isInteger(num)  ).map(filteredNum => filteredNum ** 2);

以上。

 参考にしたもの

0
0
0

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