3 回答

TA贡献1813条经验 获得超2个赞
它应该可以帮助你:
const foo = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const count = 3;
const len = foo.length / 3;
function splitInto(arr){
return Array(len).fill(0).reduce((acc, _, index) => [...acc, arr.slice(index * 3, index * 3 + 3)], [])
}
const result = splitInto(foo) // [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
我没有考虑长度不被3整除的数组。但不难弄清楚如何处理它

TA贡献1829条经验 获得超7个赞
根据你的 stackblitz 样本
import { Component, OnInit, VERSION } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
name = "Angular " + VERSION.major;
staticKpi2: {
kpi: string;
headerString: string;
footerString: string;
}[] = [];
staticKpi: {
kpi: string;
headerString: string;
footerString: string;
}[][] = [];
breakPoint = 3;
ngOnInit() {
this.populateObject();
}
populateObject() {
this.staticKpi2.push(
...[
{
kpi: "SpO2",
headerString: "High: 97 and above",
footerString: "Low: 94 and below"
},
{
kpi: "Temperature",
headerString: "High: 100.4 and above",
footerString: "Low: 94 and below"
},
{
kpi: "BP",
headerString: "High: 140/90 ",
footerString: "Low: 90/60"
},
{
kpi: "Respiratoin",
headerString: "High: 25 per min",
footerString: "Low: 10 per min"
},
{
kpi: "Pulse rate",
headerString: "High: 100 and above",
footerString: "Low: 50 and below"
},
{
kpi: "D-Dimer",
headerString: "Negative: 0.50 and Less",
footerString: "Positive: Greater than 0.50"
}
]
);
// console.log(this.staticKpi);
this.createGrouping();
}
createGrouping() {
for (let i = 0; i < this.staticKpi2.length; i += this.breakPoint) {
this.staticKpi.push([...this.staticKpi2].splice(i, this.breakPoint));
}
console.log(this.staticKpi);
}
}

TA贡献1785条经验 获得超4个赞
function createGrouping(arrData) {
let result = [];
let arr3 = [];
arrData.forEach(item => {
if(arr3.length < 3) {
arr3.push(item);
} else if(arr3.length === 3) {
result.push([...arr3]);
arr3 = [];
}
});
result = arr3.length > 0 ? result.push([...arr3]) : result;
return result;
}
添加回答
举报