Roman
Roman

Reputation: 75

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".

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

}

Upvotes: 0

Views: 133

Answers (2)

Vektor
Vektor

Reputation: 767

This solution selects all the characters in one iteration.

const altPairs = str => {
  let result = '';
  
  for(let i = 0; i < str.length; i += 4){
    result += str.substring(i, Math.min(str.length, i+2));
  }
  
  return result;
};

console.log( altPairs('kitten') );
console.log( altPairs('Chocolate') );
console.log( altPairs('CodingHorror') );

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370779

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.

Upvotes: 2

Related Questions