Iterate over a strings array and get a new string

Let say I have an array names = ["CAT", "DOG"], I want to iterate over this array to get a new name. To get a new name compare "C" of cat with "D" of "DOG" "C" comes before "D" so first letter will be "C".

Then, we will compare "A" of CAT with "D" of "DOG", again "A" comes first, so second word will be "A". Word so far is : "CA".

Then we will compare "T" of "CAT" with "D" of "DOG", this time "D" comes before "T" so third word will be "D" and so on..

Final word will be : CADOGT

Thanks in advance.

1 answer

  • answered 2018-07-11 07:09 Nina Scholz

    As I wrote in the comments, you could

    • take a result set,
    • a variable for the next compairing and
    • iterate the length,
    • take one character of the first array,
    • check and assign and save the leftover character;
    • do the same with the other array/s and
    • proceed with the next index.
    • at the and use the leftover character.

    var array = ["CAT", "DOG"],
        temp = '',
        result = '',
        i,
        l = Math.max(...array.map(s => s.length));
        
    for (i = 0; i < l; i++) {
        array.forEach(s => {
            if (!s[i]) { // early exit for smaller strings
                return;
            }
            if (temp < s[i]) {
                result += temp;
                temp = s[i];
            } else {
                result += s[i];
            }
        });
    }
    
    result += temp;
    
    console.log(result);