Ani*_*had 8 javascript arrays sorting lodash angular
我有如下数组,
let yearAndMonth = [
{ "year": 2013, "month": "FEBRUARY" },
{ "year": 2015, "month": "MARCH" },
{ "year": 2013, "month": "JANUARY" },
{ "year": 2015, "month": "FEBRUARY" }
]
Run Code Online (Sandbox Code Playgroud)
我希望按年份排序数组,然后在该年的那个月之后对数组进行排序,
我想要像这样的输出,
yearAndMonth = [
{ "year": 2013, "month": "JANUARY " },
{ "year": 2013, "month": "FEBRUARY" },
{ "year": 2015, "month": "FEBRUARY" },
{ "year": 2015, "month": "MARCH" }
]
Run Code Online (Sandbox Code Playgroud)
怎么做到这一点?
您可以采用一个对象来表示月份名称及其数值。
通过获取年和月的增量来链接订单。
var array = [{ year: 2013, month: "FEBRUARY" }, { year: 2015, month: "MARCH" }, { year: 2013, month: "JANUARY" }, { year: 2015, month: "FEBRUARY" }];
array.sort(function (a, b) {
var MONTH = { JANUARY: 0, FEBRUARY: 1, MARCH: 2, APRIL: 3, MAY: 4, JUNE: 5, JULY: 6, AUGUST: 7, SEPTEMBER: 8, OCTOBER: 9, NOVEMBER: 10, DECEMBER: 11 };
return a.year - b.year || MONTH[a.month] - MONTH[b.month];
});
console.log(array);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)
您还可以使用lodash
库按多列对数据进行排序。
我在Stackblitz上创建了一个演示 。我希望这会对您/其他人有所帮助/指导。
lodash -文档
组件.html
<table width="100%">
<tr>
<td>Year</td>
<td>Month</td>
</tr>
<tr *ngFor="let datas of sortedData">
<td>{{datas.year}}</td>
<td>{{datas.month}}</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
组件.ts
sortedData: any[];
data = [
{ "year": 2013, "month": "FEBRUARY" },
{ "year": 2015, "month": "MARCH" },
{ "year": 2013, "month": "JANUARY" },
{ "year": 2013, "month": "MARCH" },
{ "year": 2013, "month": "APRIL" },
{ "year": 2015, "month": "FEBRUARY" }
];
monthArray: any = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
"JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"];
ngOnInit() {
this.sortedData = _.orderBy(data, [(datas) => datas.year, (user) => (this.monthArray.indexOf(user.month))], ["asc", "asc"]);
console.log(this.sortedData);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1769 次 |
最近记录: |