JS:按两个不同的属性对 JSON 数组进行排序,保持数组中指定的顺序

我有一组需要排序的 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;

});

但是我不知道如何使它也遵守网站的指定顺序。


紫衣仙女
浏览 366回答 3
3回答

阿波罗的战车

如果找到的 2 个对象的文本相同,则比较 siteOrder 中 2 个对象的网站索引。data.sort(function (a, b) {&nbsp; var textA = a.found.toUpperCase();&nbsp; var textB = b.found.toUpperCase();&nbsp; var foundOrder = (textA < textB) ? -1 : (textA > textB) ? 1 : 0;&nbsp; if (foundOrder === 0) {&nbsp; &nbsp; var indexA = siteOrder.indexOf(a.website);&nbsp; &nbsp; var indexB = siteOrder.indexOf(b.website);&nbsp; &nbsp; return (indexA < indexB) ? -1 : (indexA > indexB) ? 1 : 0;&nbsp; }&nbsp; return foundOrder;});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript