• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Miscellaneous / Count the occurrences of a value in an array

Count the occurrences of a value in an array

Count the occurrences of a value in an array

Use Array.prototype.reduce() to increment a counter each time the specific value is encountered inside the array.

const countOccurrences = (arr, val) =>
  arr.reduce((a, v) => (v === val ? a + 1 : a), 0);

// EXAMPLE
countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3

Source

https://www.30secondsofcode.org/js/s/count-occurrences

Miscellaneous

Related Snippets:

  • Filtering an array of objects based on a condition
  • Return an array of elements that appear in both arrays
  • Add items to an array in JavaScript
  • Get unique values in an array

Primary Sidebar

FREE UPDATES!

Get the latest updates in your inbox for FREE!

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2023 JavaScriptSource.com

  • About
  • Privacy Policy
  • Submit
  • FAQ
  • Jobs For Developers
  • Contact Us