【发布时间】:2019-10-06 21:13:29
【问题描述】:
技术: Angular 7、AngularCli、JS 和 TS。
在Js中如何按asc和desc顺序对数组进行排序
这是我的示例数组:
this.tableRows = [
[ 'zz', 'cc' ],
[ 'aa', 'cc' ],
[ 'uu', 'dd' ]
];
我想按列位置和 asc / desc 对上面的内容进行排序。
这是我的 HTML:
<tr ls-table-row class="child-row" *ngFor="let row of tableRows">
<td ls-table-cell *ngFor="let cell of row">{{ cell }}</td>
</tr>
我将像这样传递类型和 columnPosition 的@inputs:
@Input() public sortByColumnPosiition = 1;
@Input() public sortByType = 'asc';
这些解释了我要排序的列和类型解释了方向,例如描述。
这是我当前的排序示例:
sortByColumnPosition = 0;
sortByType = 0;
public sortBy(data: Array<Array<any>>) {
return [ ...data ].sort((a, b) => a[ this.sortByColumnPosition ].localeCompare(b[ this.sortByColumnPosition ]) * this.sortByType);
}
以上是我目前的尝试 - 但仅适用于第 0 列而不适用于第 1 列
【问题讨论】:
-
请告知预期输出。
-
我想按位置排序,例如列所以 0、1 或 2,然后在 asc 和 desc 中
-
感谢@RolandStarke,我现在已经做到了——我将如何制作 asc 或 desc?
-
lodash 使这样的操作相当简单,并且在传入的集合不是数组的情况下采取了“防御性”措施。
标签: javascript arrays angular sorting multidimensional-array