gpt4 book ai didi

angularjs - 在 Controller 中使用 AngularJS 对带数字的字符串进行排序

转载 作者:行者123 更新时间:2023-12-01 03:03:47 24 4
gpt4 key购买 nike

我有这样的数据:-

$scope.crewList = [{id: 1, weekName: "crew1", dayName: "sunday"},
{id: 4, weekName: "crew11", dayName: "monday"},
{id: 3, weekName: "crew12", dayName: "tuesday"},
{id: 2, weekName: "crew10", dayName: "tuesday"},
{id: 5, weekName: "crew4", dayName: "tuesday"},
{id: 8, weekName: "crew3", dayName: "tuesday"},
{id: 12, weekName: "crew2", dayName: "tuesday"}]

并且需要按weekName排序,我正在寻找 Controller 中而不是html中的解决方案

预期的 :-
$scope.crewList = [{id: 1, weekName: "crew1", dayName: "sunday"},
{id: 12, weekName: "crew2", dayName: "tuesday"}
{id: 4, weekName: "crew3", dayName: "monday"},
{id: 3, weekName: "crew4", dayName: "tuesday"},
{id: 2, weekName: "crew10", dayName: "tuesday"},
{id: 5, weekName: "crew11", dayName: "tuesday"},
{id: 8, weekName: "crew12", dayName: "tuesday"}]

提前致谢

最佳答案

从字符串中提取数字并返回差值以对它们进行排序。

$scope.crewList.sort(({weekName : a},{weekName : b}) => (a.match(/\d+$/) || [0])[0] - (b.match(/\d+$/) || [0])[0])

const list = [{id: 1, weekName: "crew1", dayName: "sunday"},
{id: 12, weekName: "crew2", dayName: "tuesday"},
{id: 4, weekName: "crew3", dayName: "monday"},
{id: 3, weekName: "crew4", dayName: "tuesday"},
{id: 2, weekName: "crew10", dayName: "tuesday"},
{id: 5, weekName: "crew11", dayName: "tuesday"},
{id: 8, weekName: "crew12", dayName: "tuesday"}];

list.sort(({weekName : a},{weekName : b}) => a.match(/\d+$/)[0] - b.match(/\d+$/)[0]);

console.log(list)

关于angularjs - 在 Controller 中使用 AngularJS 对带数字的字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59434606/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com