Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding both characters and putting them in a new array

I’ve created a function that passes in a string and a character. The string is saturday and the character is a.

I want the result to be an array that contains all the index numbers of where the letter ‘a’ sits in saturday.

Then array ends up with only [1]. So it finds the first a sitting at the second index. I tested this by changing saturday to soturday and the console prints the array with [6].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want the result to be [1, 6]

I’ve tried putting the return result outside the next set of {} braces but no joy.

const subLength = (str, cha) => {
  let result = [];

  for (let i = 0; i < str.length; i++) {

    if (str.charAt(i) === cha) {
      result.push(str.indexOf(cha));

      return result;
    }
  }

};
console.log(subLength('Saturday', 'a'));

>Solution :

You are pretty close.

In your code the return is being executed as soon as a match is found. You want to return after you’ve checked every char – so I’ve moved it after the foreach.
indexof has a second parm, which defines the char to start looking from. If you omit it, you will get the index of the first match every time – which is not what you want.

const subLength = (str, cha) => {
  let result = [];
  
  for(let i = 0; i < str.length; i++){
    if(str[i] === cha) {
      result.push(str.indexOf(cha, i));
    }
  }
  return result;
};
console.log(subLength('Saturday', 'a'));

Room for improvement

Since you are iterating over every char anyways, you can simply store every i where str[i] matches cha.

So optimized:

const subLength = (str, cha) => {
  let result = [];
  
  for(let i = 0; i < str.length; i++){
    if(str[i] === cha) {
      result.push(i);
    }
  }
  return result;
};
console.log(subLength('Saturday', 'a'));

An even simpler version using regex:

const subLength = (str, cha) => {
  return [...str.matchAll(new RegExp(cha, 'g'))].map(e => e.index);
};
console.log(subLength('Saturday', 'a'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading