我有一个对象数组:
arr = [
{
name : 'Gary',
DOB : '01/01/1980',
importance: 'High'
},
{
name : 'Bill',
DOB : '01/01/1985',
importance: 'High'
},
{
name : 'Joe',
DOB : '01/01/1981',
importance: 'Medium'
},
{
name : 'Phillip',
DOB : '01/01/1981',
importance: 'High'
},
{
name : 'Ed',
DOB : '01/01/1980',
importance: 'Low'
},
{
name : 'Nix',
DOB : '01/01/1980',
importance: 'High'
},
{
name : 'Pat',
DOB : '01/01/1980',
importance: 'Low'
}
]
我按两个字段对这些人进行排序,首先是DOB
,如果他们有相同的 DOB,然后是重要性
,从低到高,所以低顶部和底部的高点。
我可以很容易地比较它们的日期,但之后我很难按它们的重要性排序?
有人可以提供任何建议吗?
var importanceOrder = ['Low', 'Normal', 'High'];
arr.sort(function(a, b) {
if(a.dueDate.value != b.dueDate.value){
return a.dueDate.value < b.dueDate.value ? -1 : 1;
} else {
//??
}
});
最佳答案
您可以采用一个对象作为 重要性
的排序顺序和一个用于获取 ISO 日期的函数。
const getISO = s => s.replace(/(..)\/(..)\/(....)/, '$3-$1-$2');
var array = [{ name: 'Gary', DOB: '01/01/1980', importance: 'High' }, { name: 'Bill', DOB: '01/01/1985', importance: 'High' }, { name: 'Joe', DOB: '01/01/1981', importance: 'Medium' }, { name: 'Phillip', DOB: '01/01/1981', importance: 'High' }, { name: 'Ed', DOB: '01/01/1980', importance: 'Low' }, { name: 'Nix', DOB: '01/01/1980', importance: 'High' }, { name: 'Pat', DOB: '01/01/1980', importance: 'Low' }],
order = { Low: 1, Normal: 2, High: 3 };
array.sort((a, b) => getISO(a.DOB).localeCompare(getISO(b.DOB)) || order[a.importance] - order[b.importance]);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如果日期相同,则按日期排序对象数组,然后按字符串值排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50290933/