首页 > 解决方案 > 使用“map”函数返回多个数组

问题描述

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

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

要求是将所有fromXid 拉到一个数组中,并将所有toXid 拉到另一个数组中。

有几种不同的方法,例如使用foreach, reduce, 分别为每种方法进行迭代,但是我正在寻找一种最佳的功能方法来返回具有一个映射的两个数组?

标签: javascriptecmascript-6functional-programmingreduce

解决方案


使用Array#reduce解构

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);


推荐阅读