是否可以对如下所示的数组进行排序:
array = [
{'title': 'a',
'text': 'info a1'},
{'title': 'b',
'text': 'info b1'},
{'title': 'c',
'text': 'info c1'},
{'title': 'a',
'text': 'info a2'},
{'title': 'a',
'text': 'info a3'},
{'title': 'b',
'text': 'info b2'}
]
按对排序 - 即 - 将所有不必要的字典传递到数组末尾 喜欢这个:
array = [
{'title': 'a',
'text': 'info a1'},
{'title': 'a',
'text': 'info a2'},
{'title': 'b',
'text': 'info b1'},
{'title': 'b',
'text': 'info b2'},
{'title': 'a',
'text': 'info a3'},
{'title': 'c',
'text': 'info c1'}
]
如果有帮助的话我也使用下划线。该数组还包含其他数据。我需要显示所有成对的元素。以及列表末尾没有配对的所有元素。我认为如果在显示之前对数组进行排序会更容易。
知道如何做到这一点吗?
最佳答案
也许您考虑使用 necessary
标志,然后您可以将 necessary
的真值排序到顶部,然后按 title
排序。
var array =[
{ title: 'a', text: 'info a1', necessary: true },
{ title: 'b', text: 'info b1', necessary: true },
{ title: 'c', text: 'info c1', necessary: false },
{ title: 'a', text: 'info a2', necessary: true },
{ title: 'a', text: 'info a3', necessary: false },
{ title: 'b', text: 'info b2', necessary: true }
];
array.sort(function (a, b) {
return b.necessary - a.necessary || a.title > b.title || -(a.title < b.title);
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - JS 下划线 : array of dicts in pairs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47015812/