Created
December 12, 2022 14:21
-
-
Save carlitorweb/b43cf8b2b8a67e690634d492625956a2 to your computer and use it in GitHub Desktop.
Group and count "Even - Odd" values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getEvenOddCounts (acc, val) { | |
const key = val % 2 === 0 ? "even" : "odd"; | |
acc[key] = (acc[key] ?? 0) + 1; | |
return acc; | |
} | |
const result = [1, 2, 3, 4, 5].reduce(getEvenOddCounts, {}); | |
console.log(result); // { even: 2, odd: 3 } | |
// even as a "one-liner" | |
[1, 2, 3, 4, 5].reduce((acc, val) => { const key = val % 2 === 0 ? "even" : "odd"; acc[key] = (acc[key] ?? 0) + 1; return acc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment