这个问题的独特之处在于它请求查找json对象并且不是一个简单的数组排序。我想用splitString数组的内容填充4个输入字段。但是我需要在成员[Rating]的降序(rsort)中重新排序splitString数组。成员有300多个条目,因此它适得其反,无需对其进行排序。
我该怎么做?代码是我的开始......
HTML:
<button onclick="ratingSort()" title="Rating sort" tabindex="-1">
<img src="images/sort.png" alt= "sort by rating" /></button>
<input id = "I1" />
<input id = "I2" />
<input id = "I3" />
<input id = "I4" />
和js文件:
<script type="text/javascript">
function ratingSort() {
let dataString = "Williams, Bill|Reynolds, Beverly|Smith, Paul";
let splitString = dataString.split("|");
let sorted = [];
let finalResult;
var members = [
{ "Rating": "1500", "Name": "Williams, Bill"},
{ "Rating": "2000", "Name": "Smith, Paul" },
{ "Rating": "1000", "Name": "Jones, Jim" },
{ "Rating": "1750", "Name": "Reynolds, Beverly" } ]
// sort by value
members.sort(function (a, b) {
return a.Rating - b.Rating;
});
members.map(i=>{sorted.push(i.Name)});
finalResult = sorted.filter(function(i) {return
splitString.includes(i)});
console.log(finalResult);
for (let i = 0; i < finalResult.length; i++) {
$temp = finalResult[i];
if ($temp > "") {$("#I" + i).val($temp);
$("#L" + i).css('background-color', "#7E91F8");
}
}
}
</script>
代码不起作用并产生不一致的结果。
答案 0 :(得分:0)
我建议在评级地图上创建一个&#34;名称&#34;并将该地图与排序功能一起使用。
// input data
var members = [{
"Rating": "1500",
"Name": "Williams, Bill"
},
{
"Rating": "2000",
"Name": "Smith, Paul"
},
{
"Rating": "1000",
"Name": "Jones, Jim"
},
{
"Rating": "1750",
"Name": "Reynolds, Beverly"
}
]
var toSort = "Williams, Bill|Reynolds, Beverly|Smith, Paul|Jones, Jim|".split("|");
// SOLUTION:
// create a map.
var nameRatingMap = {};
members.forEach(function(element) {
nameRatingMap[element.Name] = element.Rating;
});
console.log("name to rating map", nameRatingMap);
// use map for sorting
var sorted = toSort.sort(function(a, b) {
var ratingA = nameRatingMap[a] || 0;
var ratingB = nameRatingMap[b] || 0;
return ratingB - ratingA;
})
console.log("solution", sorted);
&#13;
答案 1 :(得分:-1)
排序功能可以让你比较评级,并返回一个更高评级的值。
使用此功能,您将在更改输入之前重新排序阵列。
下一个代码可以放在一个函数中:
members.sort(function(a, b) {
let A = a.Rating;
let B = b.Rating;
if (A > B) {
return -1;
}
if (A < B) {
return 1;
}
return 0;
});
希望这会有所帮助:)
了解更多信息 - &gt; Sort docs
var members = [
{
"Rating": "1500",
"Name": "Williams, Bill"
},
{
"Rating": "2000",
"Name": "Smith, Paul"
},
{
"Rating": "1000",
"Name": "Jones, Jim"
},
{
"Rating": "1750",
"Name": "Reynolds, Beverly"
}
];
members.sort(function(a, b) {
let A = a.Rating;
let B = b.Rating;
if (A > B) {
return -1;
}
if (A < B) {
return 1;
}
return 0;
});
for (let i = 0; i < members.length; i++) {
$("#I" + (i + 1)).val(members[i].Name);
$("#L" + i).css('background-color', "#B79EDF");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="I1" />
<input id="I2" />
<input id="I3" />
<input id="I4" />