LoginSignup
0
0

More than 5 years have passed since last update.

js 配列の正の整数を合計して返す

Last updated at Posted at 2018-05-08

与えられた配列のすべての正の整数の合計を返してください。

function positiveSum(arr) {
  //write your code
}

positiveSum([1,2,3,4,5]);//15
positiveSum([1,-2,3,4,5]);//13
positiveSum([]);//0
positiveSum([-1,-2,-3,-4,-5]);//0
positiveSum([-1,2,3,4,-5]);//9

使ったもの

filter();
length
reduce();

コード


function positiveSum(arr) {
  //正の数の判定
  let positiveNums = arr.filter((e)=>{
    return e > 0
  });
  //正の数の有無の判定
  if(positiveNums.length == 0){
    return 0
  }
  //正の数の合計
  let result = positiveNums.reduce((a,b)=>{
    return a + b;
  });
  return result
}

他コード

let positiveSum = arr => arr.filter(x => x > 0).reduce((a, b) => a+b,0);
positiveSum([1,-4,7,12]);//20

他にも解答コードある方、コメントへどうぞ

0
0
2

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