javascript - 如果其他数字是奇数,则返回“偶数”,而“奇数”其他数字是偶数 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))
解决方案
过滤两次可能更具可读性。
even = arr.filter((x) => x % 2 == 0);
odd = arr.filter((x) => x % 2 == 1);
if (even.length > odd.length) {
return even;
} else {
return odd;
}
推荐阅读
- javascript - 需要将 gpa 计算器与 HTML 中的可填写表格相关联
- rust - 为什么在实现相同的特征时,Rust 可以接受不同的结构?
- android - 如何使用 FileProvider 和 EncryptedFile?
- javascript - 使用设置间隔函数制作动画
- node.js - 当我处理错误时,NodeJS 抛出 UnhandledPromiseRejectionWarning
- android - Android 推送通知服务器实现
- javascript - 连接MongoDB Native Driver Node JS的正确方法
- javascript - 如何使用 Javascript 加载单独的 .html 页面
- python - 为什么从 google_screener_data_extract 导入 GoogleStockDataExtract 时出现 SyntaxError: invalid syntax
- sql - 如何检查json数组是否已经包含某个键?