Cracking the Logic: Finding First Occurrence in Strings

Cracking the Logic: Finding the First Occurrence! I’ve always believed that the best way to master a programming language is by building your own logic from scratch before jumping into built-in methods. Today, I worked on a classic problem: Finding the starting index of a substring within a string. The Task: Given two strings, identify the index where the second string first appears in the first one. For example: Input: ("sadbutsad", "sad") ➔ Output: 0 My Approach: Array Transformation: Split the strings into arrays to iterate through each character. Filtering Logic: Used the .filter() method to check if the main string's characters exist in the target substring using .includes(). Index Tracking: Pushed the matching indices into a temporary array. Result Extraction: Sliced the first element to get the exact starting point. The Code: JavaScript function findIdStr(a, b) { const repetArrId = [] const y = a.split('') const x = b.split('') y.filter((v, idx) => { if (x.includes(v)) { repetArrId.push(idx) } }) const result = repetArrId.slice(0, 1) console.log("Starting Index:", result[0]) } findIdStr("sadbutsad", "sad") // Output: 0 While JavaScript offers built-in tools like .indexOf(), breaking it down manually helps in understanding how data flows and how loops work under the hood. I’m curious—how would you optimize this logic? Let’s discuss in the comments! #JavaScript #WebDevelopment #ProblemSolving #CodingJourney #SoftwareEngineering #LogicBuilding #JSIndex

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories