Hone logo
Hone
Problems

Count Occurrences of a Target Value in an Array

Given an array of numbers and a specific target value, your task is to determine how many times that target value appears within the array. This is a fundamental operation in data processing, useful for tasks like frequency analysis, data validation, and searching.

Problem Description

You will be provided with two arguments:

  1. An array of numbers (arr).
  2. A target number (target).

Your goal is to write a JavaScript function that returns the total count of how many times the target number exists in the arr.

Key Requirements:

  • The function should iterate through the entire input array.
  • It should compare each element with the target value.
  • A counter should be incremented each time a match is found.
  • The function must return the final count.

Expected Behavior:

  • If the target is present in the array, return the number of times it appears.
  • If the target is not present in the array, return 0.
  • The function should handle empty arrays correctly.

Edge Cases to Consider:

  • An empty input array.
  • An array where the target appears multiple times consecutively.
  • An array where the target appears at the beginning or end.

Examples

Example 1:

Input: arr = [1, 2, 3, 2, 4, 2, 5], target = 2
Output: 3
Explanation: The number 2 appears 3 times in the array.

Example 2:

Input: arr = [10, 20, 30, 40, 50], target = 25
Output: 0
Explanation: The target value 25 does not exist in the array.

Example 3:

Input: arr = [], target = 7
Output: 0
Explanation: The input array is empty, so the target cannot be found.

Constraints

  • The input array (arr) will contain only integers.
  • The target will be an integer.
  • The length of the array will be between 0 and 1000, inclusive.
  • The values in the array and the target will be between -1000 and 1000, inclusive.
  • Your solution should have a time complexity of O(n), where n is the length of the array.

Notes

You can approach this problem using a simple loop or by leveraging built-in JavaScript array methods. Consider which method might be more efficient or readable for this specific task.

Loading editor...
javascript