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

118
Views
Search String Custom function algorithm

I want to condition the string that I Inputted value ("ello") and variable("hello").

If It found in string("hello"), the return value should be "ello". If not found, the return value should be -1.

But it returned "llll" 4 times because of condition (strs[i] == arrayS[tempVal]).

How can I get the correct answer as mentioned above?

var stres = "hello";
var strs = [...stres];

function searchStr(s) {
  let arrayS = [...s];
  let tempVal = 0;
  let tempStr = [];
  while (tempVal < arrayS.length) {
    for (let i = 0; i < strs.length; i++) {
      if (strs[i] == arrayS[tempVal]) {
        tempStr.push(arrayS[tempVal]);
      }
    }
    tempVal++;
  }

  return tempStr;
}

const res = searchStr("ello");
console.log('res', res)

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

0

According to you, logic is correct just break the for a loop when the condition is fulfilled. Check below snippet and console output.

var stres = "hello";
var strs = [...stres];

function searchStr(s) {
  let arrayS = [...s];
  let tempVal = 0;
  let tempStr = [];
  while (tempVal < arrayS.length) {
    for (let i = 0; i < strs.length; i++) {
      if (strs[i] == arrayS[tempVal]) {
        tempStr.push(arrayS[tempVal]);
        break;
      }
    }
    tempVal++;
  }
  return tempStr;
}

const res = searchStr("ello");
const resS = res.join('');
console.log('res = ', res);
console.log('resS = ', resS);

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!