Home > Software design >  How to map a js string
How to map a js string

Time:11-26

I have :

const chars = 'abcdefghijklmnopqrstuvwxyz';

I would like to create an array of strings containing

[aa,ab,ac .. zz ]

I could do it with loops but wanted to try using map.

I tried:

const baseStrings = [chars].map(x=>chars[x]).map(y=>y chars[y]);
console.log(baseStrings);

This gives:

[NaN]

What am I doing wrong?

CodePudding user response:

You have to use split

const chars = 'abcdefghijklmnopqrstuvwxyz';
const array = chars.split('')
console.log(array)

And then flatMap

const chars = 'abcdefghijklmnopqrstuvwxyz';
const array = chars.split('')

const result = array.flatMap(c1 => array.map(c2 => c1   c2))
console.log(result)

CodePudding user response:

  • Using String#split, get list of characters
  • Using Array#flatMap, iterate over this list. In each iteration, using Array#map, return a list of combinations for the current character

const chars = 'abcdefghijklmnopqrstuvwxyz';

const list = chars.split('');
const baseStrings = list.flatMap(c1 => list.map(c2 => `${c1}${c2}`));

console.log(baseStrings);

  • Related