Home > Software design >  How can I create a function to convert the string "ABCD" to an array like: ["A",
How can I create a function to convert the string "ABCD" to an array like: ["A",

Time:11-14

How can I create a function to convert the string "ABCD" to an array like: ["A", "AB", "ABC", "ABCD"] in Javascript ?


(I don't know how to exactly describe this process in English so I just put the question in the title, so, would be great if there was a special term for it to be known.. :))

CodePudding user response:

const s = 'ABCD'

function f(s) {
    return s // = 'ABCD'
        // make array of length s.length
        .split('') // = ['A','B','C','D']
        // map it to slices of length (i 1)
        .map(
            (
                e,// = 'A','B','C','D'
                i, // = 0,1,2,3
            ) => s.slice(0, i   1)
        ) // = what you said
}

console.log(f(s))

CodePudding user response:

One way to do it, without any fancy stuff, just a basic for loop:

    var str = 'ABCD'
    var new_str = '';
    var arr_string = new Array();
    
    for (var i = 0; i < str.length; i  ) {
        new_str  = str.charAt(i);
        arr_string[i] = new_str
    }
    
    console.log(arr_string);

CodePudding user response:

this way...?

console.log( foo('ABCD') );

function foo(str)
  {
  let res = [], s='';
  for (let c of str) res.push( s =c );
  return res;
  }

Or ?

const foo = str => Array.from(str,(_,i) => str.slice(0,i 1));
 
console.log( foo('ABCD') )

CodePudding user response:

A more readable approach:

const getProgressiveArray = (string) => {
  let concat = '';
  const progressiveArray = [];

  for (let character of string) {
    concat  = character;
    progressiveArray.push(concat);
  }

  return progressiveArray;
};

Remember, a string is iterable, making issues like this more straightforward. Pairing this fact with the for...of loop, can result in a concise and readable solution.

Hope this helps.

CodePudding user response:

Using Array.from and concat methods

const getWords = (word, res = "") =>
  Array.from(word, (c) => (res = res.concat(c)));
  

console.log(getWords("ABCD"))

  • Related