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

How to return a string made of the chars at indexes?

I feel like my solution is just way too complicated. If anyone can suggest an easier one, would be great.

It’s a challenge from coding bat. The task is:

Given a string, return a string made of the chars at indexes 0,1, 4,5,
8,9 … so "kittens" yields "kien".

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

Examples

altPairs('kitten') → kien
altPairs('Chocolate') → Chole
altPairs('CodingHorror') → Congrr

My solution (works fine, but seems too amateur):

function altPairs(str) {

    // convert the string to an Array 

    let newArr = str.split("")

    //  create two emtpy Arrays to fill in with the characters of certain indexes from original Array

    // myArrOne will contain indexes 0,4,8...
    let myArrOne = [];

    // myArrTwo will contain indexes 1,5,9...
    let myArrTwo = [];

    // Loop through the original Array 2 times to push elements into myArrOne and myArrTwo

    for (let i = 0; i < newArr.length; i += 4) {
        myArrOne.push(newArr[i])
    }
    for (let i = 1; i < newArr.length; i += 4) {
        myArrTwo.push(newArr[i])
    }

    // create new Array. Loop through myArrTwo and myArrOne and push element to myArrtThree

    let myArrThree =[];
    for (let i = 0; i <= myArrOne.length && i <= myArrTwo.length; i++){
        myArrThree.push(myArrOne[i], myArrTwo[i])
    }

    // myArrThree to a new string with join method

    let myString = myArrThree.join('')
    
    return myString

}

>Solution :

A concise approach would be to use a regular expression: match and capture 2 characters, then match up to 2 more characters, and replace with the 2 captured characters. Replace over all the string.

const altPairs = str => str.replace(
  /(..).{0,2}/g,
  '$1'
);

console.log(altPairs('kitten'))//  → kien
console.log(altPairs('Chocolate'))//  → Chole
console.log(altPairs('CodingHorror'))// → Congrr
  • (..) – match and capture 2 characters (first capture group)
  • .{0,2} – match zero to two characters

Replacing with $1 replaces with the contents of the first capture group.

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