Angular--返回数组内嵌套着数组排序法

(118) 2024-05-20 10:01:01

// ===================================  html文件  ====================================

<nz-table #nzTable [nzData]="list">

<thead (nzSortChange)="sort($event)" nzSingleSort>

<tr>

<th nzShowSort nzSortKey="serIal"></th>

<th nzShowSort nzSortKey="conCen"></th>

<th nzShowSort nzSortKey="fie001"></th>

<th nzShowSort nzSortKey="fie002"></th>

<th nzShowSort nzSortKey="fie003"></th>

<th nzShowSort nzSortKey="fie004"></th>

</tr>

</thead>

<tbody>

<ng-container ngfor=" let item of list;index as i">

<tr ngfor=" let data of item.data;index as i">

<td>{
{data.serIal}}</td>

<td>{
{data.conCen}}</td>

<td>{
{data.fie001}}</td>

<td>{
{data.fie002}}</td>

<td>{
{data.fie003}}</td>

<td>{
{data.fie004}}</td>

</tr>

</ng-container>

</tbody>

</nz-table>

// ====================================  ts文件  =====================================

// 定义排序参数

public sortName = null;

public sortValue = null;

// 数组结构

public list= [{serIal:'序号',conCen:'内容',data:[

{fie001:'数据1',fie002:'数据2',fie003:'数据3',fie004:'数据4'},

{fie001:'数据1',fie002:'数据2',fie003:'数据3',fie004:'数据4'},

]},

{serIal:'序号',conCen:'内容',data:[

{fie001:'数据1',fie002:'数据2',fie003:'数据3',fie004:'数据4'},

{fie001:'数据1',fie002:'数据2',fie003:'数据3',fie004:'数据4'},

]}

];

// 分组排序逻辑

sort(sort: {key:string,value:string} ):void {

this.sortName = sort.key;

this.sortValue= sort.key;

if(sort.value === 'ascend') {

for(let i = 0; i < this.list.length; i++){

for(let j = 0; j < this.list[i].data.length; j++){

for(let k = 0; k< this.list[i].data.length; k++){

if(sort.key === 'conCen'){

this.list[i].data.sort(function(a,b){

return b.conCen.localeCompare(a.conCen, 'zh');

});

}else if(this.list[i].data[k][sort.key] > this.list[i].data[j][sort.key]) {

const temp = this.list[i].data[k];

this.list[i].data[k] = this.list[i].data[j];

this.list[i].data[j] = temp;

}

}

}

}

}else if(sort.value === 'descend') {

for(let i = 0; i < this.list.length; i++){

for(let j = 0; j < this.list[i].data.length; j++){

for(let k = 0; k< this.list[i].data.length; k++){

if(sort.key === 'conCen'){

this.list[i].data.sort (function(a, b) {

return a.conCen.localeCompare (b.conCen, 'zh');

});

}else if(this.list[i].data[k][sort.key] < this.list[i].data[j][sort.key]) {

const temp = this.list[i].data[k];

this.list[i].data[k] = this.list[i].data[j];

this.list[i].data[j] = temp;

}

}

}

}

}

}

小生不才,如有不足之处,请批评指正。

THE END

发表回复