javascript - 使用 "map"函数返回多个数组

标签 javascript ecmascript-6 functional-programming reduce

我的代码有一个元素数组,如下所示:

element: { fromX: { id: ... } , toX: { id: ... } }

要求是将所有 fromX id 拉入一个数组,并将所有 toX id 拉入另一个数组。

有几种不同的方法, 例如使用 foreachreduce,分别迭代每个,但我正在寻找一种最佳的功能方法来通过一个映射返回两个数组?

最佳答案

使用Array#reducedestructuring

const data=[{fromX:{id:1},toX:{id:2}},{fromX:{id:3},toX:{id:4}},{fromX:{id:5},toX:{id:6}},{fromX:{id:7},toX:{id:8}}]

const [fromX,toX] = data.reduce(([a,b], {fromX,toX})=>{
  a.push(fromX.id);
  b.push(toX.id);
  return [a,b];
}, [[],[]]);

console.log(fromX);
console.log(toX);

关于javascript - 使用 "map"函数返回多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54201304/

相关文章:

javascript - jquery:如果在 div 内或不在 div 内,则单击鼠标

javascript - 数组文字中是否有动态索引的表示法?

Javascript ES6 检索类的成员

列表 Monad : Consequences of the signature of List. flatMap(f: (A) ⇒ GenTraversableOnce[B])

function - OCaml 递归函数应用一个函数 n 次

javascript - 具有 Promise 的 Node js Controller 的多个退出点

javascript - 如何从 Node.js 模块正确返回一组实例

javascript - 为什么 HttpRequest 回调在没有警报的情况下不起作用

javascript - ES6 模板文字 : How to pass a scope before they are interpreted?

haskell - 如何在 Haskell 中比较非 'Eq' 类型?