首页 > 解决方案 > 如果其他数字是奇数,则返回“偶数”,而“奇数”其他数字是偶数 javascript

问题描述

我有 2 个问题,如何在数组中获取值而不是值,以及如何使这段代码更短且具有声明性。

arr = [16, 4, 11, 20, 2]

arrP = [7, 4, 11, 3, 41]

arrTest = [2, 4, 0, 100, 4, 7, 2602, 36]

function findOutlier(arr) {
  const isPair = (num) => num % 2 === 0
  countEven = 0
  countOdd = 0
  arr1 = []
  arr2 = []
  const result = arr.filter((ele, i) => {
    if (isPair(ele)) {
      countEven++
      arr1.push(ele)

    } else {
      countOdd++

      arr2.push(ele)
    }

  })
  return countEven > countOdd ? arr2 : arr1

}

console.log(findOutlier(arrTest))

标签: javascriptarraysoutliersdeclarative

解决方案


过滤两次可能更具可读性。

even = arr.filter((x) => x % 2 == 0);
odd = arr.filter((x) => x % 2 == 1);
if (even.length > odd.length) {
    return even;
} else {
    return odd;
}

推荐阅读