1

I want to store 15 string characters in an array index and the next 15 characters in the other index.

Array index 0 = "123456789012345" Array index 1 = "678901234567890"

            var newData:String[] = [];
            let word = "";
            let Inctext = "1234567890123456789012345678901234567890123456789012345678901234567890";
           
            for (let i = 0; i < Inctext.length; i++)
            {
               word +=  Inctext[i]
               console.log(word)
               newData[i] = word
               console.log(newData)

            }

Array index 0 = "123456789012345" Array index 1 = "678901234567890" and so on...

1 Answer 1

1
const word = "1234567890123456789012345678901234567890123456789012345678901234567890";
const chunkedWord = [];
for (let i = 0; i < (word.length / 15); i++) {
    const chunkStart = i * 15;
    const chunkEnd = chunkStart + 15;
    chunkedWord[i] = word.slice(chunkStart, chunkEnd);
}
console.log(chunkedWord)

The for loop iterates n times, whereas n is the length of word divided by 15. Hence, each iteration deals with a 15 character chunk of word. For each chunk we calculate its start and end. The start of a chunk is its position (starting from 0) in the chunk array multiplied by the chunk length (15). The end is the chunk start incremented by the chunk length (15).

Based on chunkStart and chunkEnd, we slice a 15 character chunk out of word and assign it to the corresponding index of chunkedWord. By doing word.length / 15 in the for loop, we make sure that chunkedWord has the right amount of indices.

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

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.