[英]How to sort an array of objects based on scores - Javascript
I have an array of objects that contain the data I want to sort (it has more properties), like so:我有一个对象数组,其中包含我要排序的数据(它有更多属性),如下所示:
[
{
"data": {
"id": "green"
}
},
{
"data": {
"id": "red"
}
},
{
"data": {
"id": "blue"
}
}
]
id
is a nested property I need to use in order to sort based on scores provided from a different object like so: id
是我需要使用的嵌套属性,以便根据从不同对象提供的分数进行排序,如下所示:
{
"green": 5,
"red": 3,
"blue": 8
}
I'm trying to find the best way to sort my array of object, however no success so far.我正在尝试找到对我的对象数组进行排序的最佳方法,但是到目前为止还没有成功。
Javascripts built-in sort function has a optional comparison function parameter. Javascripts 内置的排序函数有一个可选的比较函数参数。 The following code utilizes this function to solve your problem:
以下代码利用此功能解决您的问题:
var array = [ { "data": { "id": "green" } }, { "data": { "id": "red" } }, { "data": { "id": "blue" } } ]; var scores = { "green": 5, "red": 3, "blue": 8 }; array.sort((a, b) => (scores[a.data.id] - scores[b.data.id])); console.log(array);
You can sort them like this: https://jsfiddle.net/Ldvja31t/1/你可以像这样对它们进行排序: https ://jsfiddle.net/Ldvja31t/1/
const scores = {
"green": 5,
"red": 3,
"blue": 8
};
const myData = [
{
"data": {
"id": "green"
}
},
{
"data": {
"id": "red"
}
},
{
"data": {
"id": "blue"
}
}
];
myData.sort((d1, d2) => {
return scores[d1.data.id] - scores[d2.data.id]
});
console.log(myData)
The two answers that were given should work fine.给出的两个答案应该可以正常工作。 However I would also like to add you could use an Enum.
但是我还想补充一点,您可以使用枚举。 Example
例子
Heres a separate example of an enum usage and sorting it in an array of objects这是枚举用法的单独示例并将其排序到对象数组中
const enum Order {
Start = 'Start',
Run = 'Run',
End = 'End',
}
const predicate = (a, b) => {
const map = {};
map[Order.Start] = 1;
map[Order.Run] = 2;
map[Order.End] = 3;
if (map[a] < map[b]) {
return -1;
}
if (map[a] > map[b]) {
return 1;
}
return 0;
}
const data = [Order.End, Order.Run, Order.Start];
const result = data.sort(predicate);
console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.