简体   繁体   English

返回奇数和空数组的函数

[英]Function that returns array with odd numbers and null

I've a task to write function that returns the average value of even numbers from an array.我的任务是编写函数,该函数从数组中返回偶数的平均值。 If there are no even numbers in the array, return null.如果数组中没有偶数,则返回 null。 Here are arrays and expected result: [1,2,3,4,5,6,7] - should return "4" and [1,1,1,1] - should return "null".以下是数组和预期结果: [1,2,3,4,5,6,7] - 应该返回“4”,[1,1,1,1] - 应该返回“null”。 Where shall I put condition for null?I've tried different options but nothing works but maybe my code is wrong.我应该在哪里设置 null 的条件?我尝试了不同的选项,但没有任何效果,但也许我的代码是错误的。

 function getEvenAverage(array) { const even = array.filter(function (element) { return element % 2 === 0 }); const sum = even.reduce(function (sum, element) { return (sum + element); }); return sum / even.length; } const result1 = getEvenAverage([1,2,3,4,5,6,7]) console.log(result1); const result2 = getEvenAverage([1,1,1,1]) console.log(result2);

You can achieve this in 1 loop as well:您也可以在 1 个循环中实现此目的:

Logic:逻辑:

  • Create an object(say map ) to hold values创建一个对象(比如map )来保存值
  • Loop on array.在数组上循环。
  • Check if current item is even, compute total and length.检查当前项目是否是偶数,计算总数和长度。 Set it to map将其设置为map
  • At the end, check for length and return value最后,检查长度和返回值

 function getEvenAverage(array) { const map = array.reduce((acc, item) => { if (item % 2 === 0) { return { total: acc.total + item, length: acc.length + 1 } } return acc }, { total: 0, length: 0 }); return map.length ? map.total / map.length : null } const result1 = getEvenAverage([1, 2, 3, 4, 5, 6, 7]) console.log(result1); const result2 = getEvenAverage([1, 1, 1, 1]) console.log(result2);

check this code检查此代码

  function getEvenAverage (arr) {
  let temp = [];
  let sum = 0;
  let count = 0;
  arr.map(item => {
    if(item % 2 === 0) {
      temp = [...temp, item]
    }
  })
  temp.map(item => {
    sum += item;
    count +=1;
  })
  if(temp.length ===0) {
    return null
  }
  return sum/count;
}

You need to do the following changes:您需要进行以下更改:

  1. Add null as an initial value for Array.prototype.reduce添加null作为Array.prototype.reduce的初始值
  2. Check if sum === null return sum , otherwise calculate an average value检查sum === null是否返回sum ,否则计算平均值

You can find the code with changed applied below您可以在下面找到已更改应用的代码

 function getEvenAverage(array) { const even = array.filter(function (element) { return element % 2 === 0 }); const sum = even.reduce(function (sum, element) { return (sum + element); }, null); return sum === null ? sum : sum / even.length; } const result1 = getEvenAverage([1,2,3,4,5,6,7]) console.log(result1); const result2 = getEvenAverage([1,1,1,1]) console.log(result2);

Originally posted as a simple edit to this answer .最初作为对此答案的简单编辑发布。 Reposting as a separate answer below (as the other answer-er, Rajesh rolled back & noted that this be posted separately).在下面重新发布为单独的答案(作为另一个答案, Rajesh回滚并指出这将单独发布)。

Added comments as this is now posted as a separate answer.添加了评论,因为这现在作为单独的答案发布。

 // method to get average of even numbers in array const getEvenAverage = (arr) => ( arr // use optional-chainging "?." to handle bad "arr" values ?.reduce( // iterate over the array (acc, itm, idx) => { // access "acc" (accumulator), "itm" and "idx" if (itm % 2 === 0) { // if itm is even number acc.tot += itm; // add it to "acc" total (ie, "tot" prop) acc.len++; // increment the "len" prop of "acc" }; if ( // if processing last "itm" idx === arr.length - 1 && acc.len > 0 // and have previously processed even number "itm" ) { // update "result" prop of "acc" acc.result = acc.tot / acc.len; }; return acc; // return the updated "acc" for each iteration }, // initialize "acc" to have three props { tot: 0, len: 0, result: null } ) // simply send the "result" back to the caller ?.result ); console.log( 'call fn with array: 1,2...7\naverage-of-even-numbers: ', getEvenAverage([1, 2, 3, 4, 5, 6, 7]) ); console.log( 'call fn with array: 1,1,1,1\naverage-of-even-numbers: ', getEvenAverage([1, 1, 1, 1]) ); console.log( 'call fn with empty-array: []\naverage-of-even-numbers: ', getEvenAverage([]) ); console.log( 'call fn with undefined: \naverage-of-even-numbers: ', getEvenAverage() );
 .as-console-wrapper { max-height: 100% !important; top: 0 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM