0

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?

user1592380
  • 34,265
  • 92
  • 284
  • 515
  • 1
    Did you mean `[...chars]` instead of `[chars]`? What’s the purpose of `.map(x=>chars[x])`? How about using `console.log` to check the _intermediate_ results instead of the useless final result? – Sebastian Simon Nov 25 '22 at 19:15
  • Is it every combo? like "ba" would be in it? – epascarello Nov 25 '22 at 19:23

3 Answers3

1

const chars = 'abcdefghijklmnopqrstuvwxyz';

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

console.log(baseStrings);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
1

You can use [...string] instead of String.split:

console.log([...'abcdefghijklmnopqrstuvwxyz']
  .flatMap((i,_,a)=>a.map(j=>i+j)))
Andrew Parks
  • 6,358
  • 2
  • 12
  • 27
0

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)
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • 2
    `split` will not get a list of characters, but a list of UTF-16 byte pairs. That’s why `Array.from` or `...` is preferred. See [Do NOT use `.split('')`](/a/38901550/4642212). – Sebastian Simon Nov 25 '22 at 20:01