我有一系列行:
this.lines = [
0: {indexLine: 0, group: 16, columns: [,…]}
1: {indexLine: 1, group: 16,…}
2: {indexLine: 2, group: 16,…}
3: {indexLine: 3, group: 9,…}
]
我想按組對行進行分組,以便能夠在不同的表格中呈現它。
我試過這個:
let arr: any = {};
this.lines.forEach((line) => {
if (!arr[line.group]) {
arr[line.group] = [];
}
arr[line.group].push(line);
});
uj5u.com熱心網友回復:
您可以使用從物件陣列中Set獲取唯一group值。new Set(lines.map(x => x.group)將為您提供組的唯一值陣列。
將該集合轉換為陣列Array.from()。
現在您可以使用 map 遍歷唯一的組值,并Array.filter為您提供所有匹配的元素。
let lines = [
{indexLine: 0, group: 16},
{indexLine: 1, group: 16},
{indexLine: 2, group: 16},
{indexLine: 3, group: 9},
];
const groupedLines = Array.from(new Set(lines.map(x=>x.group))).map(y => lines.filter(z => z.group === y));
console.log(groupedLines);
uj5u.com熱心網友回復:
你可以使用reduce方法來得到你想要的:
const result = this.lines.reduce((acc, item) => {
if (!acc[item.group]) {
acc[item.group] = [];
}
acc[item.group].push(item);
return acc;
}, {});
如果您想將所有組作為多個陣列而不是一個物件,您可以Object.values這樣做:
const groups = Object.values(result);
uj5u.com熱心網友回復:
你可以使用lodash.groupBy
yarn add lodash.groupby(或npm install lodash.groupby --save)
import groupBy from 'lodash.groupby'; // 12.6k (gzipped 4.8k)
// ...
console.log(groupBy(this.lines, ({group}) => group)));
(不言自明的代碼,每分鐘 0 個 WTF)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/476979.html
標籤:javascript 有角度的
上一篇:對字串進行條件評估
