Array.map 1 element to multiple element

前端 未结 10 693
一整个雨季
一整个雨季 2021-02-01 02:23

I have [3, 16, 120]. when I do [3, 16, 120].map(mapper), I want to achieve, for example [4,5, 17,18, 121,122] i.e. each element map to n

相关标签:
10条回答
  • 2021-02-01 03:15

    Using Array.prototype.flat():

    const doubled = [3, 16, 120].map(item => [item + 1, item + 2]).flat();
    
    console.log(doubled)

    Fair warning – not a standard method to this date (posted 12/2018).

    0 讨论(0)
  • 2021-02-01 03:17

    you could produce an array for each items, then concat all these arrays :

    [3, 16, 120].map(x => [x+1, x+2] ).reduce( (acc,val) => acc.concat(val), []);
    
    0 讨论(0)
  • 2021-02-01 03:20

    2019 Update

    Use Array.prototype.flatMap(), introduced in ES10.

    const oddNumbers = [1, 3, 5, 7, 9];
    const allNumbers = oddNumbers.flatMap((number) => [number, number + 1]);
    console.log(allNumbers); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    0 讨论(0)
  • 2021-02-01 03:21

    I come up with one myself, using spread operator.

    [].concat(...[3, 16, 120].map(x => [x+1, x+2]))

    0 讨论(0)
提交回复
热议问题