[英]javascript sorting by value, if the values are equal, sorting between equal items by a different value
I have an object data, I sort this data according to their points, but if the points are the same, I want the last updated item to be on top.我有一个对象数据,我根据它们的点对这些数据进行排序,但如果点相同,我希望最后更新的项目位于顶部。 but I could not create the algorithm here.但我无法在这里创建算法。 Can you help me ?你能帮助我吗 ?
My JSON Data我的 JSON 数据
[
{
"name": "Item 1",
"point": 3,
"updatedAt": "10/06/2022 9:39"
},
{
"name": "Item 2",
"point": 4,
"updatedAt": "10/06/2022 9:45"
},
{
"name": "Item 3",
"point": 2,
"updatedAt": "10/06/2022 9:39"
},
{
"name": "Item 4",
"point": 1,
"updatedAt": "10/06/2022 9:39"
},
{
"name": "Item 5",
"point": 5,
"updatedAt": "10/06/2022 9:39"
},
{
"name": "Item 6",
"point": 2,
"updatedAt": "11/06/2022 3:05"
}
]
For example, the points of Item 3 and Item 6 are the equal here, but Item 3 displays at the top.例如,这里第 3 项和第 6项的点是相等的,但第 3 项显示在顶部。 Because I added Item 6 later.因为我后来添加了第 6 项。 So how do I get Item 6 to be above Item 3 if their points are equal?那么,如果他们的分数相等,我如何让第 6 项高于第 3 项?
I was planning to do this so that the last updated is at the top.我打算这样做,以便最后更新的内容位于顶部。
I tried several methods but it didn't work, for now this is my starting code.我尝试了几种方法,但没有奏效,现在这是我的起始代码。
if (sortBy === "lowtohigh") {
computedData = data.sort((a, b) => {
return a.point - b.point
});
}
if (sortBy === "hightolow") {
computedData = data.sort((a, b) => {
return b.point - a.point
});
}
Thank you for your answers in advance.提前感谢您的回答。
Using Array#sort
and Date
(as fallback):使用Array#sort
和Date
(作为后备):
const arr = [ { "name": "Item 1", "point": 3, "updatedAt": "10/06/2022 9:39" }, { "name": "Item 2", "point": 4, "updatedAt": "10/06/2022 9:45" }, { "name": "Item 3", "point": 2, "updatedAt": "10/06/2022 9:39" }, { "name": "Item 4", "point": 1, "updatedAt": "10/06/2022 9:39" }, { "name": "Item 5", "point": 5, "updatedAt": "10/06/2022 9:39" }, { "name": "Item 6", "point": 2, "updatedAt": "11/06/2022 3:05" } ]; const res = arr.sort((a, b) => a.point - b.point || new Date(b.updatedAt) - new Date(a.updatedAt) ); console.log(res);
If later numbered items have that naming convention and are always the most recently updated, check the order of items if points are equal:如果后面编号的项目具有该命名约定并且始终是最近更新的,请检查项目的顺序(如果点数相等):
computedData = data.sort((a, b) => {
if (a.point - b.point) return a.point - b.point; // Change this line depending on asc or desc sort.
else {
return Number(a.name.split(" ")[1]) - Number(b.name.split(" ")[1]);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.