user1592380
user1592380

Reputation: 36227

How to map a js string

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?

Upvotes: 0

Views: 3535

Answers (3)

Majed Badawi
Majed Badawi

Reputation: 28414

const chars = 'abcdefghijklmnopqrstuvwxyz';

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

console.log(baseStrings);

Upvotes: 1

Andrew Parks
Andrew Parks

Reputation: 8087

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

console.log([...'abcdefghijklmnopqrstuvwxyz']
  .flatMap((i,_,a)=>a.map(j=>i+j)))

Upvotes: 1

Konrad
Konrad

Reputation: 24661

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)

Upvotes: 0

Related Questions