skip to Main Content

I want to take the first character of each item in an array and join those to create a new string. Then i want to do the same with the second characters, third characters, and finally 4th characters.

For example I have the following array:

let arr = ["abcd", "efgh, "ijkl", "mnop"]

would then turn into the string…

"aeim"
"bfjn"
"cgko"
"dhlp"

3

Answers


  1. Assuming that each element in the array has the same length, you could iterate over all indexes and use Array#map and Array#join to construct a string from all the characters at that index.

    (If you want to get the length of the shortest string when they have different lengths, you can use Math.min(...arr.map(s => s.length)).)

    let arr = ["abcd", "efgh", "ijkl", "mnop"];
    const res = Array.from({length: arr[0].length}, (_, i) => 
                  arr.map(s => s[i]).join(''));
    console.log(res);
    Login or Signup to reply.
  2. You can achieve this by using a combination of the Array#map and Array#join it back to string:

    let arr = ["abcd", "efgh", "ijkl", "mnop"];
    let result = Array.from({ length: arr[0].length }, (_, i) =>
      arr.map((item) => item[i]).join("")
    );
    console.log(result.join("n"));

    Output:

    aeim
    bfjn
    cgko
    dhlp
    
    Login or Signup to reply.
  3. Another method is to iterate over each position in the strings with simply two for-loops:

    let arr = ["abcd", "efgh", "ijkl", "mnop"];
    let result = [];
    
    for (let i = 0; i < arr[0].length; i++) {
      let currentString = "";
      for (let j = 0; j < arr.length; j++) {
        currentString += arr[j].charAt(i);
      }
      result.push(currentString);
    }
    
    console.log(result.join("n"));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search