Topic describes

General idea: first of all, establish the corresponding relationship between numbers and letters

 const map = new Map([[2['a'.'b'.'c']],
    [3['d'.'e'.'f']], [4['g'.'h'.'i']],
    [5['j'.'k'.'l']], [6['m'.'n'.'o']],
    [7['p'.'q'.'r'.'s']], [8['t'.'u'.'v']],
    [9['w'.'x'.'y'.'z']]]);Copy the code

It then iterates through the parameter string and pushes the array corresponding to the character into an array, generating a two-dimensional array

 // '234' => [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
 const tmp: string[] [] = [];for (let i = 0; i < digits.length; ++i) {
    if(map.has(+digits[i])) tmp.push(map.get(+digits[i])!) ; }Copy the code

At last,reduceConvert the two-dimensional array to the corresponding result

let res: string[] = [];
// Consider the boundary case
if(! digits ||Array.from(digits).some((item) = > +item < 2)) return res;
Array.prototype.flat(); // We can also use es6's array.prototype.flat ()
res = tmp.reduce((res, current) = > flatArray<string>(res.map((r) = > current.map((c) = > r + c))));

// Array flat
export function flatArray<T> (arr: any[]) :T[] {
  return arr.reduce((res, current) = > Array.isArray(current) ? [...res, ...flatArray(current)] :
    [...res, current], []);
}


// Test the code
  it('letterCombinations'.() = > {
    expect(letterCombinations(' ')).toEqual([]);
    expect(letterCombinations('1')).toEqual([]);
    expect(letterCombinations('123')).toEqual([]);
    expect(letterCombinations('23')).toEqual(['ad'.'ae'.'af'.'bd'.'be'.'bf'.'cd'.'ce'.'cf']);
    expect(letterCombinations('234')).toEqual([
      'adg'.'adh'.'adi'.'aeg'.'aeh'.'aei'.'afg'.'afh'.'afi'.'bdg'.'bdh'.'bdi'.'beg'.'beh'.'bei'.'bfg'.'bfh'.'bfi'.'cdg'.'cdh'.'cdi'.'ceg'.'ceh'.'cei'.'cfg'.'cfh'.'cfi'
    ]);
  });

  it('flatArray'.() = > {
    expect(flatArray([[]])).toEqual([]);
    expect(flatArray([[1.2.3], [4.5.6]])).toEqual([1.2.3.4.5.6]);
    expect(flatArray([[1.2.3]])).toEqual([1.2.3]);
    expect(flatArray([[[1], [2], [3]], [[4], [5], [6]]])).toEqual([1.2.3.4.5.6]);
    expect(flatArray([[1The [[2]], [3]], [[4], [5], [6]]])).toEqual([1.2.3.4.5.6]);
  });
Copy the code

Submit the record