我有一组需要排序的 JSON 对象。数组需要按两个不同的属性排序。首先,数组应按found属性按字母顺序排序。其次,应该对数组进行排序,以便website属性按照 中指定的相同顺序下降siteOrder。
var siteOrder = ['facebook', 'twitter', 'reddit', 'youtube', 'instagram'];
var data = [
{found: 'booker', website: 'reddit'},
{found: 'john', website: 'facebook'},
{found: 'walter', website: 'twitter'},
{found: 'smith', website: 'instagram'},
{found: 'steve', website: 'youtube'},
{found: 'smith', website: 'facebook'},
{found: 'steve', website: 'twitter'},
{found: 'john', website: 'instagram'},
{found: 'walter', website: 'youtube'}
];
/* Example output: Sorted output by found, respecting the order of the websites specified
{found: 'booker', website: 'reddit'},
{found: 'john', website: 'facebook'},
{found: 'john', website: 'instagram'},
{found: 'smith', website: 'facebook'},
{found: 'smith', website: 'instagram'},
{found: 'steve', website: 'twitter'},
{found: 'steve', website: 'youtube'},
{found: 'walter', website: 'twitter'},
{found: 'walter', website: 'youtube'}
*/
我可以使用以下方法按找到的属性按字母顺序排序:
data.sort(function(a, b) {
var textA = a.found.toUpperCase();
var textB = b.found.toUpperCase();
return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
});
但是我不知道如何使它也遵守网站的指定顺序。
阿波罗的战车
相关分类