0
0
DSA Javascriptprogramming~15 mins

Count Occurrences of Element in Sorted Array in DSA Javascript - Build from Scratch

Choose your learning style9 modes available
Count Occurrences of Element in Sorted Array
📖 Scenario: You have a sorted list of product IDs from a store's sales records. You want to find out how many times a specific product was sold.
🎯 Goal: Build a program that counts how many times a given product ID appears in the sorted array.
📋 What You'll Learn
Create an array called productIDs with the exact values: [101, 101, 102, 103, 103, 103, 104, 105]
Create a variable called targetID and set it to 103
Use a for loop with variable id to iterate over productIDs
Inside the loop, count how many times targetID appears
Print the count with console.log
💡 Why This Matters
🌍 Real World
Counting how many times a product was sold helps stores understand popular items and manage inventory.
💼 Career
This skill is useful for data analysis, software development, and any job that involves processing lists of data efficiently.
Progress0 / 4 steps
1
Create the sorted array of product IDs
Create an array called productIDs with these exact values: [101, 101, 102, 103, 103, 103, 104, 105]
DSA Javascript
Hint

Use const to create the array named productIDs with the given numbers.

2
Set the target product ID to count
Create a variable called targetID and set it to 103
DSA Javascript
Hint

Use const to create targetID and assign it the value 103.

3
Count how many times the target ID appears
Create a variable called count and set it to 0. Then use a for loop with variable id to iterate over productIDs. Inside the loop, increase count by 1 each time id equals targetID.
DSA Javascript
Hint

Start count at 0. Use a for...of loop to check each id in productIDs. Increase count when id matches targetID.

4
Print the count of the target product ID
Use console.log to print the value of count
DSA Javascript
Hint

Use console.log(count); to show the number of times targetID appears.