【问题标题】:Return multiple arrays using "map" function使用“map”函数返回多个数组
【发布时间】:2019-06-09 14:37:38
【问题描述】:

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

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

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

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

【问题讨论】:

  • 一个对象是否只有两个属性?
  • 能否提供更全面的输入输出?谢谢。
  • 您期望得到什么?包含两个具有映射值的数组的数组?
  • 您能否再扩展一下示例代码以显示完整的结构?即,当显示多个 fromXfromY 值时会是什么样子?
  • [froms, tos] = transpose(elements.map(e => [e.fromX, e.toX])) 是函数式的方式——不幸的是,JS 中没有原生的 transpose 函数

标签: javascript ecmascript-6 functional-programming reduce


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以使用以下解决方案来实现此目的

    var array = [{ fromX: { id: 1 }, toX: { id: 2 } }, { fromX: { id: 3 }, toX: { id: 4 } }], 
     arrayX = array.map(x => x.fromX), arraytoX = array.map(toX => toX.toX)
    
    console.log(arrayX);
    console.log(arraytoX );

    【讨论】:

      【解决方案3】:

      您可以为想要的键获取一个数组并映射该值。稍后请destructuring assignment 获得单身id

      const
          transpose = array => array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []),
          array = [{ fromX: { id: 1 }, toX: { id: 2 } }, { fromX: { id: 3 }, toX: { id: 4 } }],
          keys = ['fromX', 'toX'],
          [fromX, toX] = transpose(array.map(o => keys.map(k => o[k].id)));
      
      console.log(fromX);
      console.log(toX);

      【讨论】:

      • 我相信您的回答不符合“我想将所有 fromX id 拉到一个数组中,并将所有 toX id 拉到另一个数组中”的问题的一个要求。
      • @thibpat,请参阅fromXtoX
      • 运行 sn-p 时,我得到:fromX = [1,2]toX = [3,4]。我相信预期的结果是fromX = [1, 3]toX = [2, 4]
      【解决方案4】:

      试试这个:

      const arr = [{
        fromX: {
          id: 1
        },
        toX: {
          id: 2
        }
      }, {
        fromX: {
          id: 3
        },
        toX: {
          id: 4
        }
      }]
      let {
        arr1,
        arr2
      } = arr.reduce((acc, {
        fromX,
        toX
      }) => ({ ...acc,
        arr1: [...acc.arr1, fromX],
        arr2: [...acc.arr2, toX]
      }), {
        arr1: [],
        arr2: []
      })
      console.log(arr1, arr2);

      【讨论】:

        猜你喜欢
        • 2018-04-09
        • 1970-01-01
        • 2021-12-30
        • 2017-09-23
        • 1970-01-01
        • 2017-07-16
        • 1970-01-01
        • 2018-12-11
        相关资源
        最近更新 更多