我如何根据数字和特定字母对对象数组进行排序?
How can i sort array of objects based on numbers and spefific letters?
我有这个数组
let arr = [
{
"time": "3",
"wholeObj": "abc mo sa 3 Y",
"mapEventValue": "Y"
},
{
"time": "3",
"wholeObj": "abc a 3 G",
"mapEventValue": "G"
},
{
"time": "3",
"wholeObj": "cba d 3 S f",
"mapEventValue": "S"
},
{
"time": "3",
"wholeObj": "cba z 3 R",
"mapEventValue": "R"
}
]
我需要首先根据 time
值对数组进行排序,然后如果时间值相等,我需要根据 mapEventValue 对它们进行排序
按照以下顺序 G Y R S
所以在我的例子中,所有对象都具有相同的时间值 3
我找不到按 mapEventValue
属性
对它们进行排序的方法
我试过的
到目前为止,我只是设法按时间值对它们进行排序
让排序 = arr.sort((a,b) => a.time - b.time)
所以我最后的输出应该是
let arr = [
{
"time": "3",
"wholeObj": "abc a 3 G",
"mapEventValue": "G"
},
{
"time": "3",
"wholeObj": "abc mo sa 3 Y",
"mapEventValue": "Y"
},
{
"time": "3",
"wholeObj": "cba z 3 R",
"mapEventValue": "R"
},
{
"time": "3",
"wholeObj": "cba d 3 S f",
"mapEventValue": "S"
},
]
因此,如果 time
不同,则仅按 time
排序,否则按所需排序顺序的索引排序。
let sortOrder = 'GYRS';
let arr = [
{
"time": "3",
"wholeObj": "abc mo sa 3 Y",
"mapEventValue": "Y"
},
{
"time": "3",
"wholeObj": "abc a 3 G",
"mapEventValue": "G"
},
{
"time": "3",
"wholeObj": "cba d 3 S f",
"mapEventValue": "S"
},
{
"time": "3",
"wholeObj": "cba z 3 R",
"mapEventValue": "R"
}
];
let sorted = arr.sort((a,b) => {
if (a.time != b.time) {
return a.time - b.time;
} else {
return sortOrder.indexOf(a.mapEventValue) - sortOrder.indexOf(b.mapEventValue);
}
});
console.log(sorted);
我有这个数组
let arr = [
{
"time": "3",
"wholeObj": "abc mo sa 3 Y",
"mapEventValue": "Y"
},
{
"time": "3",
"wholeObj": "abc a 3 G",
"mapEventValue": "G"
},
{
"time": "3",
"wholeObj": "cba d 3 S f",
"mapEventValue": "S"
},
{
"time": "3",
"wholeObj": "cba z 3 R",
"mapEventValue": "R"
}
]
我需要首先根据 time
值对数组进行排序,然后如果时间值相等,我需要根据 mapEventValue 对它们进行排序
按照以下顺序 G Y R S
所以在我的例子中,所有对象都具有相同的时间值 3
我找不到按 mapEventValue
属性
我试过的
到目前为止,我只是设法按时间值对它们进行排序
让排序 = arr.sort((a,b) => a.time - b.time)
所以我最后的输出应该是
let arr = [
{
"time": "3",
"wholeObj": "abc a 3 G",
"mapEventValue": "G"
},
{
"time": "3",
"wholeObj": "abc mo sa 3 Y",
"mapEventValue": "Y"
},
{
"time": "3",
"wholeObj": "cba z 3 R",
"mapEventValue": "R"
},
{
"time": "3",
"wholeObj": "cba d 3 S f",
"mapEventValue": "S"
},
]
因此,如果 time
不同,则仅按 time
排序,否则按所需排序顺序的索引排序。
let sortOrder = 'GYRS';
let arr = [
{
"time": "3",
"wholeObj": "abc mo sa 3 Y",
"mapEventValue": "Y"
},
{
"time": "3",
"wholeObj": "abc a 3 G",
"mapEventValue": "G"
},
{
"time": "3",
"wholeObj": "cba d 3 S f",
"mapEventValue": "S"
},
{
"time": "3",
"wholeObj": "cba z 3 R",
"mapEventValue": "R"
}
];
let sorted = arr.sort((a,b) => {
if (a.time != b.time) {
return a.time - b.time;
} else {
return sortOrder.indexOf(a.mapEventValue) - sortOrder.indexOf(b.mapEventValue);
}
});
console.log(sorted);