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
}
CodePudding user response:
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.
CodePudding user response:
This solution selects the characters in one iteration. It'll check if a character exists at the successive index of str
before concatenating to the resultant string.
const altPairs = str => {
let result = '';
for(let i = 0; i < str.length; i = 4){
result = str[i];
(str[i 1]) && (result = str[i 1]);
}
return result;
};
console.log( altPairs('kitten') );
console.log( altPairs('Chocolate') );
console.log( altPairs('CodingHorror') );