Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

205
Views
i need to find the distance between two characters in string js. i have a solution but i can't understand the snippet of code related to if statement

The task was to write a function subLength() that takes 2 parameters, a string and a single character. The function should search the string for the two occurrences of the character and return the length between them including the 2 characters. If there are less than 2 or more than 2 occurrences of the character the function should return 0.

const subLength = (str, char) => {
let charCount = 0;
let len = -1;

for (let i=0; i<str.length; i++) {
  if (str[i] == char) {
    charCount++;
    if (charCount > 2) {
      return 0;
    }
// could somebody explain why -1 is equal to len and then len is reassigned to i???       
if (len == -1) {
      len = i;
    } else {
      len = i - len + 1
    }
  }
}
if (charCount < 2) {
  return 0;
}

return len;
};

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

in the first occurrence len= -1 so: (len ==-1) turned to true; and len is changed to i so len=i; in the second occurance len is not -1 so:

len = i - len -1;

in essence, in the above expression, len keeps the index of the first occurrence, and i has the index of second occurrence, so the difference will be, the difference between two occurrences, 'qweraq' : first occurrance: 0, second: 6. 6-0-1= 5 is difference;

about 4 years ago · Juan Pablo Isaza Report

0

This is how I manage to rewrite your code. Hope this helps.

const subLength = (str, char) => {
  const arr = str.split('');
  let count = 0;
  arr.forEach(letter => letter === char ? count++ : '')
  const result = arr.some(letter => {
    if (arr.indexOf(char) !== arr.lastIndexOf(char) && count == 2) {
      return true
    }
    return false
  })
  return result ? Math.abs(arr.indexOf(char) - arr.lastIndexOf(char)) + 1 : 0
}

about 4 years ago · Juan Pablo Isaza Report

0

Whilst its possible to calculate the indexes and the count within a single loop, given the triviality I'd favor standard API methods for scanning. one could always optimize later if the application actually called for it.

First we convert the string to an array so that we have the ability to filter for matches to the input character, and derive the length.

Only if there are 2 occurrences do we calculate the distance between using the indexOf and lastIndexOf methods on string (note that these will only require a second full scan of the string if the two occurrences are consecutive).

Otherwise, the result should be 0.

const subLength = (str, chr) => {

    const count = str.split('').filter(ltr => ltr === chr).length
    if (count === 2) {
        return (str.lastIndexOf(chr) - str.indexOf(chr)) + 1
    }
    return 0
}


console.log(subLength('asddfghvcba', 'a'))
console.log(subLength('asddfghvcba', 'x'))
console.log(subLength('aaaaaaaaaaa', 'a'))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!