Reputation: 36227
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
Reputation: 28414
spread-operator
, get list of charactersArray#flatMap
, iterate over this list. In each iteration, using Array#map
, return a list of combinations for the current characterconst chars = 'abcdefghijklmnopqrstuvwxyz';
const list = [...chars];
const baseStrings = list.flatMap(c1 => list.map(c2 => `${c1}${c2}`));
console.log(baseStrings);
Upvotes: 1
Reputation: 8087
You can use [...string]
instead of String.split:
console.log([...'abcdefghijklmnopqrstuvwxyz']
.flatMap((i,_,a)=>a.map(j=>i+j)))
Upvotes: 1
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