Skip to content

Instantly share code, notes, and snippets.

@carlitorweb
Created December 12, 2022 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlitorweb/b43cf8b2b8a67e690634d492625956a2 to your computer and use it in GitHub Desktop.
Save carlitorweb/b43cf8b2b8a67e690634d492625956a2 to your computer and use it in GitHub Desktop.
Group and count "Even - Odd" values
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