0
0
DSA Javascriptprogramming~15 mins

First and Last Occurrence of Element in DSA Javascript - Build from Scratch

Choose your learning style9 modes available
First and Last Occurrence of Element
📖 Scenario: Imagine you have a list of daily temperatures recorded over a week. You want to find out on which days a specific temperature first and last appeared.
🎯 Goal: You will create a program that finds the first and last positions of a given temperature in the list.
📋 What You'll Learn
Create an array called temperatures with exact values: [23, 25, 23, 22, 25, 26, 23]
Create a variable called targetTemp and set it to 23
Write code to find the first and last occurrence indexes of targetTemp in temperatures
Print the first and last occurrence indexes in the format: First occurrence: X and Last occurrence: Y
💡 Why This Matters
🌍 Real World
Finding first and last occurrences helps in analyzing repeated events, like tracking when a temperature first and last appeared in weather data.
💼 Career
This skill is useful in data analysis, debugging logs, and searching through records efficiently.
Progress0 / 4 steps
1
Create the temperature list
Create an array called temperatures with these exact values: [23, 25, 23, 22, 25, 26, 23]
DSA Javascript
Hint

Use const temperatures = [23, 25, 23, 22, 25, 26, 23]; to create the array.

2
Set the target temperature
Create a variable called targetTemp and set it to 23
DSA Javascript
Hint

Use const targetTemp = 23; to set the target temperature.

3
Find first and last occurrence indexes
Create two variables called firstIndex and lastIndex. Use temperatures.indexOf(targetTemp) to find the first occurrence and temperatures.lastIndexOf(targetTemp) to find the last occurrence.
DSA Javascript
Hint

Use indexOf and lastIndexOf methods on the array.

4
Print the results
Print the first occurrence index with console.log("First occurrence: " + firstIndex) and the last occurrence index with console.log("Last occurrence: " + lastIndex).
DSA Javascript
Hint

Use console.log to print the results exactly as shown.