最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - expand sub-array to named lambda arguments in someArray.map() - Stack Overflow

programmeradmin2浏览0评论

I have an array A:

const A = [
    [1, 2],
    [3, 4],
    [5, 6]
];

Is there a possibility to call map in a way that the sub arrays are expanded to named arguments of the lambda?

For instance, I want this:

const B = A.map((a, b) => a + b);

Instead of:

const B = A.map(e => e[0] + e[1]);

I have an array A:

const A = [
    [1, 2],
    [3, 4],
    [5, 6]
];

Is there a possibility to call map in a way that the sub arrays are expanded to named arguments of the lambda?

For instance, I want this:

const B = A.map((a, b) => a + b);

Instead of:

const B = A.map(e => e[0] + e[1]);
Share Improve this question edited Mar 18 at 23:47 Spectric 32.4k6 gold badges29 silver badges54 bronze badges asked Mar 18 at 23:41 vlad_tepeschvlad_tepesch 6,9471 gold badge44 silver badges87 bronze badges 1
  • 1 No, there's no way to make map itself do that. But it would be relatively trivial to use a different callback function, or write a wrapper to map which does that, or write a wrapper for the callback function. – Bergi Commented Mar 19 at 0:38
Add a comment  | 

1 Answer 1

Reset to default 4

Sounds like a job for array destructuring:

const A = [[1,2],[3,4],[5,6]];

const B = A.map(([a,b]) => a + b);
console.log(B)

发布评论

评论列表(0)

  1. 暂无评论