将数组作为Observable <any []>中的值拆分为较小的块

时间:2019-05-13 13:54:53

标签: angular rxjs

我花了几个小时在Observable的对象数组上复制一个过程,但是我没有运气来完成它!

想象一下,我们有一个像这样的大型数组作为可观察对象:

[ 
  {name: "you1", id: 32}, 
  {name: "you2", id: 12}, 
  {name: "you3", id: 22},
  {name: "you4", id: 54}, 
  {name: "you", id: 09},
  {name: "you", id: 43}, 
  ....
]

,您想将它们按3个数组分组,每个数组都有2个类似项:

[ 
  [{name: "you1", id: 32}, {name: "you2", id: 12}], 
  [{name: "you3", id: 22}, {name: "you4", id: 54}], 
  [{name: "you", id: 09}, {name: "you", id: 43}], 
  ....
]

此范围是动态的,我们需要进行一些计算并将Observable值转换为这种形式。好吧,我很容易用Javascript完成它,但是我不知道如何用RXJS完成它。有帮助吗?

这是在JS中完成的方式:

        let positionArray,
            positionItem = 0;
        const totalArray = this.groupedBySize > 0 ? Math.floor(size(this.selectedWorkspaces) / this.groupedBySize) : 0;
        this.selectedGroupedWorkspaces = [];

        for (positionArray = 0; positionArray < totalArray; positionArray += 1) {
            this.selectedGroupedWorkspaces[positionArray] = this.selectedWorkspaces.slice(
                positionItem,
                positionItem + this.groupedBySize
            );
            positionItem = positionItem + this.groupedBySize;
        }
        if (positionArray < totalArray || positionArray === 0) {
            this.selectedGroupedWorkspaces[positionArray] = this.selectedWorkspaces.slice(positionItem);
        }

        this.workspaces$ = of(this.selectedGroupedWorkspaces);

1 个答案:

答案 0 :(得分:1)

只不过是减少数组:

const data = new rxjs.BehaviorSubject([ 
  {name: "you1", id: 32}, 
  {name: "you2", id: 12}, 
  {name: "you3", id: 22},
  {name: "you4", id: 54}, 
  {name: "you", id: 09},
  {name: "you", id: 43}, 
]);

const grouped = data.pipe(rxjs.operators.map(arr => arr.reduce((p, n) => {
  
  const last = p[0];
  if (last.length < 3) last.push(n);
  else p.unshift([n]);
  
  return p;
}, [[]]).reverse()));

grouped.subscribe(d => console.log(d));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.2/rxjs.umd.js"></script>

您甚至可以创建自定义rxjs运算符:

const data = new rxjs.BehaviorSubject([ 
  {name: "you1", id: 32}, 
  {name: "you2", id: 12}, 
  {name: "you3", id: 22},
  {name: "you4", id: 54}, 
  {name: "you", id: 09},
  {name: "you", id: 43}, 
]);

const groupArrayByGroupOf = length => rxjs.operators.map(arr => arr.reduce((p, n) => {
  
  const last = p[0];
  if (last.length < length) last.push(n);
  else p.unshift([n]);
  
  return p;
}, [[]]).reverse())

const grouped = data.pipe(groupArrayByGroupOf(3));

grouped.subscribe(d => console.log(d));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.2/rxjs.umd.js"></script>