What if you could find the first and last place of anything in a list without missing a beat?
Why First and Last Occurrence of Element in DSA Javascript?
Imagine you have a long list of names, and you want to find where a particular name first appears and where it appears last.
Doing this by looking at each name one by one can be tiring and confusing, especially if the list is very long.
Manually scanning through the list takes a lot of time and you might miss the first or last spot by mistake.
It's easy to get lost or confused, especially if the name appears many times.
Using a simple method to find the first and last place of the name quickly helps you avoid mistakes and saves time.
This method checks the list just once and remembers the first and last spots automatically.
let index = -1; for (let i = 0; i < arr.length; i++) { if (arr[i] === target) { index = i; // keeps updating } } console.log(index);
let first = -1, last = -1; for (let i = 0; i < arr.length; i++) { if (arr[i] === target) { if (first === -1) first = i; last = i; } } console.log({first, last});
This lets you quickly find the exact start and end positions of any item in a list, making searching easy and reliable.
Think about searching for a word in a book to see where it first appears and where it last appears to understand its importance or context.
Manually searching is slow and error-prone.
Using a simple loop to track first and last positions is fast and accurate.
This method helps in many searching and data analysis tasks.