使用减少,地图和传播的笛卡尔乘积将需要平坦化的结果分组 [英] Cartesian product using reduce, map and spread is grouping the result which need to be flattened

查看:88
本文介绍了使用减少,地图和传播的笛卡尔乘积将需要平坦化的结果分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

集合$ {
构造函数(arr){
super(arr);
}
union(set){
return new MathSet([... this,... set])
}
intersection(set){
返回新的MathSet([... this] .filter(x => set.has(x)));
}
差(集){
返回新的MathSet([... this] .filter(x =>!set.has(x)));
}
cartesian(set){
return new MathSet([... this] .reduce((acc,i)=> [... acc,[... set ] .map(j => [i,j])],[]))
}
}

let x = new MathSet([1,2,3 ]);
let y = new MathSet([1,2,3,4,5]);

console.log(JSON.stringify([... x.cartesian(y)]));
// [
// [[1,1],[1,2],[1,3],[1,4],[1,5]],
/ / [[2,1],[2,2],[2,3],[2,4],[2,5]],
// [[3,1],[3,2 ],[3,3],[3,4],[3,5]]
//]

使用 cartesian 函数预期结果是上述数组的平面版本( [[1,1],[1,2 ],[1,3],[1,4],[1,5],[2,1],[2,2],[2,3],[2,4],[2,5], [3,1],[3,2],[3,3],[3,4],[3,5]] ),但是你可以看到它被分为三个阵列。减少是保持连接早期结果与新结果的扩展版本。任何猜测我做错了什么?

解决方案

要平铺数组,您只需要一个扩展:

 返回新的MathSet([... this] .reduce((acc,i)=> [... acc,... [ ... set] .map(j => [i,j])],[]))
// ^^^

(或 acc.concat(Array.from(set,j => [i,j]))


class MathSet extends Set{
  constructor(arr){
     super(arr);
     }
  union(set){
     return new MathSet([...this, ...set])
  }
  intersection(set){
     return new MathSet([...this].filter(x => set.has(x)));
  }
  difference(set){
     return new MathSet([...this].filter(x => !set.has(x)));
  }
  cartesian(set){
     return new MathSet( [...this].reduce((acc, i)=> [...acc, [...set].map(j=>[i,j])], []) )
  }
}

let x = new MathSet([1,2,3]);
let y = new MathSet([1,2,3,4,5]);

console.log(JSON.stringify([...x.cartesian(y)]));
//[
//  [[1,1],[1,2],[1,3],[1,4],[1,5]],
//  [[2,1],[2,2],[2,3],[2,4],[2,5]],
//  [[3,1],[3,2],[3,3],[3,4],[3,5]]
// ]

With cartesian function expected result is a flattened version of the above array ([[1,1],[1,2],[1,3],[1,4],[1,5],[2,1],[2,2],[2,3],[2,4],[2,5],[3,1],[3,2],[3,3],[3,4],[3,5]]), but as you can see somehow its getting grouped into three arrays. The reduce is keeping on concatenating earlier result with spreaded version of new results. Any guess on what I am doing wrong?

解决方案

To flatten the arrays you need just one more spread:

return new MathSet( [...this].reduce((acc, i)=> [...acc, ...[...set].map(j=>[i,j])], []) )
//                                                       ^^^

(or acc.concat(Array.from(set, j=>[i,j])))

这篇关于使用减少,地图和传播的笛卡尔乘积将需要平坦化的结果分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆