gpt4 book ai didi

javascript - 按字母顺序排序总是将所有文本推为第一个选项

转载 作者:行者123 更新时间:2023-11-29 10:30:54 26 4
gpt4 key购买 nike

我一直在尝试按字符串对下面的数组进行排序,它工作正常。但要注意的是,文本“ALL”应该始终出现在列表的顶部。由于它是按字母顺序排序的,所以文本“ALL”被移动到它的自然字母位置。要求是排序后,它应该在列表的第一个元素中。如何以最佳方式做到这一点?

 <div ng-controller="MyCtrl">
<ul ng-repeat="strVal in arrVal|orderBy:'toString()'" >
<li>{{strVal}}</li>
</ul>
</div>

var app=angular.module('myApp', []);
app.controller('MyCtrl', function ($scope,$filter) {
$scope.arrVal = ['All','Alabama','Alaska','American Samoa','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','District of Columbia','Federated States of Micronesia','Florida','Georgia','Guam','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Marshall Islands','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Northern Mariana Islands','Ohio','Oklahoma','Oregon','Palau','Pennsylvania','Puerto Rico','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virgin Island','Virginia','Washington','West Virginia','Wisconsin','Wyoming']

});

最佳答案

很简单,你只需要在.sort()中添加一个额外的条件即可。 回调以优先考虑 All 字符串,因此它应该始终被首先处理。

arr.sort(function(a, b) {
var nameA = a.toUpperCase();
var nameB = b.toUpperCase();
if (nameA === "ALL") {
return -1;
} else if (nameB === "ALL") {
return 1;
}
//The rest of the code

演示:

这是一个演示:

var arr = ['All', 'Alabama', 'Alaska', 'American Samoa', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'District of Columbia', 'Federated States of Micronesia', 'Florida', 'Georgia', 'Guam', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Marshall Islands', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Northern Mariana Islands', 'Ohio', 'Oklahoma', 'Oregon', 'Palau', 'Pennsylvania', 'Puerto Rico', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virgin Island', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'];


var results = arr.sort(function(a, b) {
var nameA = a.toUpperCase();
var nameB = b.toUpperCase();
if (nameA === "ALL") {
return -1;
} else if (nameB === "ALL") {
return 1;
} else {
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
}

// names must be equal
return 0;
});
console.log(results);

关于javascript - 按字母顺序排序总是将所有文本推为第一个选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46356434/

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