Array.map 1 element to multiple element

前端 未结 10 692
一整个雨季
一整个雨季 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:05

    You can use reduce() and add to array e+1, e+2 of each element.

    var ar = [3, 16, 120];
    
    var result = ar.reduce(function(r, e) {
      r.push(e+1, e+2);
      return r;
    }, []);
    
    console.log(result)

    This is ES6 version with arrow function

    var ar = [3, 16, 120];
    
    var result = ar.reduce((r, e) => r.push(e+1, e+2) && r, []);
    console.log(result)

    PS: Array.push seems to be faster and has no Maximum call stack.. error, see below:

    a = Array(1000000).fill(1); st = Date.now(); Array.prototype.concat.apply([], a.map(function (n) { return [n+1, n+2]; })); console.log(`${Date.now() - st}ms `);
    > RangeError: Maximum call stack size exceeded
    
    a = Array(1000000).fill(1); st = Date.now(); a.reduce((r, e) => r.push(e+1, e+2) && r, []); console.log(`${Date.now() - st}ms `);
    > 180ms
    

    So .push is preferable comparing to accepted solution.

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

    You could use Array#reduce in combination with Array#concat.

    console.log([3, 16, 120].reduce(function (r, a) {
        return r.concat(a + 1, a + 2);
    }, []));

    ES6

    console.log([3, 16, 120].reduce((r, a) => r.concat(a + 1, a + 2), []));

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

    using Array#concat and Array#map

    Array.prototype.concat.apply([], [3, 16, 120].map(x => [x+1, x+2] ));
    
    0 讨论(0)
  • 2021-02-01 03:12

    Not particularly nice, but it is a possible solution:

    var arr = [3, 16, 120];
    
    console.log([].concat.apply([], arr.map(function (n) { return [n+1, n+2]; })));

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

    Just for fun, an ES6 solution with a generator:

    var arr = [3, 16, 120];
    
    var [...result] = (function*() { for( i of arr){ yield ++i; yield ++i; }})();
    
    console.log(result);

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

    Immutable solution, with the spread operator:

    [3, 16, 120].reduce((a, v) => [...a, v+1, v+2], [])
    
    0 讨论(0)
提交回复
热议问题