Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

arrays - return "even" if others numbers are odd and "odd" the others number are even javascript

I have 2 questions, how can I get value instead of value inside array and how can I make this code shorter and declarative.

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Filtering twice may be more readable.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...