0

So I'm trying to split a string to in two different strings

I want to make a function that will take first letter from the string and push it to another string, then take second letter and push it to another string, then restart the loop and start from the place it stopped

Example:

imagine i have this string let string = ['SOMEMESSAGE'];

and i want it to be like this:

let firtsLetters = ['SMMSAE'];
let secondLetters= ['OEESG'];
4
  • 1
    I have a feeling this may be some homework assignment. Commented Apr 15, 2020 at 10:12
  • 1
    Where is your actual attempt here? This is not a code-writing service, you are supposed to show what you actually tried first of all. Commented Apr 15, 2020 at 10:13
  • 1
    Rather trivial using a loop, index-based character access and string concatenation … jsfiddle.net/sg6to0j7 Commented Apr 15, 2020 at 10:17
  • 1
    And btw., a string, and an array containing one string, are different things. Commented Apr 15, 2020 at 10:18

2 Answers 2

2

You could for example split the string into an array, thenArray#filter over it, according to the index of currently looped element. Then - join the array to get the string.

const string = 'SOMEMESSAGE';

const firstLetters = [...string].filter((_, i) => !(i % 2)).join('');
const secondLetters = [...string].filter((_, i) => i % 2).join('');

console.log(firstLetters);
console.log(secondLetters);

Sign up to request clarification or add additional context in comments.

Comments

0

As you mentioned your string is an array of strings. Like this

let text = ['SOMEMESSAGE', 'MYNAME'];

If you want to loop through an arrays of strings you can use following.

let text = ['SOMEMESSAGE', 'MYNAME'];

            let arrya1 = [];
            let array2 = [];

            text.forEach((ch,i)=>
            {
                x = 0;
                for(var n of ch) {
                     (x % 2 == 0) ? arrya1.push(ch.charAt(x)) : array2.push(ch.charAt(x))
                     x++;
                }
            });

             const firstLetters = arrya1.join('');
             const secondLetters = array2.join('');

    console.log(text);
    console.log(firstLetters);
    console.log(secondLetters);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.