gpt4 book ai didi

javascript - 除世界之外按字母顺序排列项目

转载 作者:行者123 更新时间:2023-11-30 11:45:51 25 4
gpt4 key购买 nike

我有以下使用 d3 填充两个组合框。

现场演示在这里:http://plnkr.co/edit/NRGa5YqvCSNraveH5Ci0?p=preview

我如何确保组合框中的国家/地区始终按字母顺序显示 - 除了“world”(世界)应该始终是组合框中出现的第一个项目?

例如,如果选择了 XXX,我想要这个订单

world
aruba
uk
usa

代码如下:

<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>comboBoxWithRadios</title>
<script src="https://d3js.org/d3.v3.js"></script>
<style type="text/css">
#projection-menu {
left: 5px;
top: 45px;
}

#category-menu {
left: 75px;
top: 5px;
}
</style>
</head>

<body>
<select id="category-menu"></select>
<select id="projection-menu"></select>
<script type="text/javascript">
var exampleCSV = "comboBoxWithRadios.csv"
var defaultCountry = "world";



updateCategoryCombo();
updateGeoCombo();

function updateCategoryCombo(geo) {

d3.csv(exampleCSV, function(rows) {

var menu = d3.select("#category-menu")
.on("change", function () {
updateGeoCombo(this.value);
});
menu.selectAll("option")
.data(d3.map(rows, function(d) {
return d.category;
}).keys())
.enter()
.append("option")
.text(function(d) {
return d;
});
});
};




function updateGeoCombo(categ) {

d3.csv(exampleCSV, function(rows) {
dta = rows.filter(function(row) {
if (row['category'] == categ) {
return true;
}
});

//clear combobox
removeOptions(document.getElementById("projection-menu"));

var menu = d3.select("#projection-menu")
.on("change", changeGeo);
menu.selectAll("option")
.data(d3.map(dta, function(d) {
return d.country;
}).keys())
.enter()
.append("option")
.text(function(d) {
return d;
});
});
};

function changeGeo() {
updateCategoryCombo(this.value);
};


function removeOptions(selectbox) {
var i;
for (i = selectbox.options.length - 1; i >= 0; i--) {
selectbox.remove(i);
}
}
</script>
</body>

</html>

最佳答案

要使用一个单词或一组单词的优先级对数组进行排序,您可以使用一个对象作为排序顺序,并为所有其他单词使用默认值。

var array = ['usa', 'uk', 'aruba', 'world'],
order = { default: 0, world: -1 };

array.sort(function (a, b) {
return (order[a] || order.default) - (order[b] || order.default) || a.localeCompare(b);
});

console.log(array);

关于javascript - 除世界之外按字母顺序排列项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41005671/

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