将多维数组上的Array.reduce转换为对象数组

时间:2016-12-20 01:12:30

标签: javascript arrays functional-programming poker

在我的扑克应用程序中,我有一排手,每一手都是随机选择的卡片对象,有价值和适合:

[ [ { value: 5, suit: 's' },
    { value: 4, suit: 's' },
    { value: 6, suit: 'c' },
    { value: 11, suit: 'd' },
    { value: 12, suit: 'c' } ],
  [ { value: 9, suit: 'd' },
    { value: 12, suit: 'h' },
    { value: 8, suit: 'c' },
    { value: 12, suit: 's' },
    { value: 2, suit: 's' } ],
  [ { value: 4, suit: 'h' },
    { value: 6, suit: 's' },
    { value: 10, suit: 'c' },
    { value: 3, suit: 'd' },
    { value: 7, suit: 'd' } ] ]

为了准备评估的手,我想使用Array.reduce返回一个手对象数组。所以输出将是:

[ 
  { 
    values: [5, 4, 6, 11, 12],
    suits: ['s', 's', 'c', 'd', 'c'] 
  },      
  { 
    values: [9, 12, 8, 12, 2], 
    suits: ['d', 'h', 'c', 's', 's'] 
  },
  { 
    values: [4, 6, 10, 3, 7],
    suits: ['h', 's', 'c', 'd', 'd'] 
  } 
]

我尝试用嵌套的forEach实现这个,但它失败了,我不知道为什么。我有两个console.log,其中输出符合预期,但最终指针与输入相同。

let temp = []
hands.forEach((el) => {
  temp = el
  el = {}
  el.values = []
  el.suits = []
  console.log(el) //expected output
  temp.forEach((obj) => {
    el.values.push(obj.value)
    el.suits.push(obj.suit)
    console.log(el) //expected output
  })
})
console.log(hands) //same as original

3 个答案:

答案 0 :(得分:7)

您必须考虑输入数据的形状(DATA)和输出(DATA'

enter image description here

请注意HANDHAND'之间的 1:1 关系,这意味着我们将Array.prototype.map用于一次转换。另一方面,CARDHAND' N:1 关系,我们会使用Array.prototype.reduce进行转换

enter image description here

因此,在我们工作的时候请记住,我们将做一个地图减少

const data = 
  [ [ { value: 5, suit: 's' },
      { value: 4, suit: 's' },
      { value: 6, suit: 'c' },
      { value: 11, suit: 'd' },
      { value: 12, suit: 'c' } ],
    [ { value: 9, suit: 'd' },
      { value: 12, suit: 'h' },
      { value: 8, suit: 'c' },
      { value: 12, suit: 's' },
      { value: 2, suit: 's' } ],
    [ { value: 4, suit: 'h' },
      { value: 6, suit: 's' },
      { value: 10, suit: 'c' },
      { value: 3, suit: 'd' },
      { value: 7, suit: 'd' } ] ]

let output = 
  data.map(cards =>
    cards.reduce(({values, suits}, {value, suit}) => ({
      values: [...values, value],
      suits: [...suits, suit]
    }), {values: [], suits: []}))

console.log(output)

现在当然看起来有点密集,所以如果我们能够稍微降低复杂性,那就太好了。通过为mapreduce制作一些curried适配器,我们可以表达一个能很好地执行转换的函数

const data = 
  [ [ { value: 5, suit: 's' },
      { value: 4, suit: 's' },
      { value: 6, suit: 'c' },
      { value: 11, suit: 'd' },
      { value: 12, suit: 'c' } ],
    [ { value: 9, suit: 'd' },
      { value: 12, suit: 'h' },
      { value: 8, suit: 'c' },
      { value: 12, suit: 's' },
      { value: 2, suit: 's' } ],
    [ { value: 4, suit: 'h' },
      { value: 6, suit: 's' },
      { value: 10, suit: 'c' },
      { value: 3, suit: 'd' },
      { value: 7, suit: 'd' } ] ]


const map = f => xs => xs.map(f)

const reduce = f => y => xs => xs.reduce(f, y)

const handAppendCard = ({values, suits}, {value, suit}) => ({
  values: [...values, value],
  suits: [...suits, suit]
})

const makeHands =
  map (reduce (handAppendCard) ({values:[], suits:[]}))

let output = makeHands (data)

console.log(output)

这只是解决问题的一种方法。我希望你能从中学到一些东西^ _ ^

答案 1 :(得分:1)

你去了 - 使用嵌套Array.prototype.reduce函数的解决方案:

var array=[[{value:5,suit:'s'},{value:4,suit:'s'},{value:6,suit:'c'},{value:11,suit:'d'},{value:12,suit:'c'}],[{value:9,suit:'d'},{value:12,suit:'h'},{value:8,suit:'c'},{value:12,suit:'s'},{value:2,suit:'s'}],[{value:4,suit:'h'},{value:6,suit:'s'},{value:10,suit:'c'},{value:3,suit:'d'},{value:7,suit:'d'}]];

var result = array.reduce(function(p, c) {
      p.push(c.reduce(function(a, b) {
        a.values.push(b.value);
        a.suits.push(b.suit);
        return a;
      }, {values: [],suits: []}));
    return p;
  },[]);

console.log(result);
.as-console-wrapper {top: 0;max-height: 100%!important;}

答案 2 :(得分:-1)

以下是string concatreduce的简单解决方案。你可以尝试类似的东西:

var reduced = []; 
//here a is your initial array
for(var i=0; i<a.length;i++){
    reduced.push(a[i].reduce(function(prev,curr){
        var obj={value:prev.value+','+curr.value,suit:prev.suit+','+curr.suit};return obj}));
}
console.log(reduced)

编辑:根据@Barmar评论,这会返回字符串。如果你想要一个数组,你可以这样做:

for(var i=0; i<a.length;i++){
    var tempElm =a[i].reduce(function(prev,curr) {
        var obj= {value:prev.value+','+curr.value,suit:prev.suit+','+curr.suit};return obj}); 
        tempElm['value'] = tempElm['value'].split();
        tempElm['suit']= tempElm['suit'].split();
        reduced.push(tempElm);
}
console.log(reduced)

编辑2:对上述修复程序的公平批评(增加了将字符串转换为数组的头脑)您可以直接创建数组,如下所示:

var reduced = []; 
for(var i=0; i<a.length;i++){ 
    var valArray = []; var suitArray=[];
    var tempElm = a[i].reduce(function(prev,curr) {
        valArray.push(curr.value);suitArray.push(curr.suit);
        var obj= {value:valArray,suit:suitArray};
        return obj;
    },null); 
console.log(reduced)