2017-05-29 56 views
0

我按类型排序此类型的数组:是否有可能基于JavaScript中的另一个对象对排序后的数组进行排序?

const bands = [ 
    { genre: 'Rap', band: 'Migos', albums: 2}, 
    { genre: 'Pop', band: 'Coldplay', albums: 4, awards: 10}, 
    { genre: 'Pop', band: 'xxx', albums: 4, awards: 11}, 
    { genre: 'Pop', band: 'yyyy', albums: 4, awards: 12}, 
    { genre: 'Rock', band: 'Breaking zzzz', albums: 1} 
    { genre: 'Rock', band: 'Breaking Benjamins', albums: 1} 
]; 

有了这个:

function compare(a, b) { 
    // Use toUpperCase() to ignore character casing 
    const genreA = a.genre.toUpperCase(); 
    const genreB = b.genre.toUpperCase(); 

    let comparison = 0; 
    if (genreA > genreB) { 
    comparison = 1; 
    } else if (genreA < genreB) { 
    comparison = -1; 
    } 
    return comparison; 
} 

由于描述here 但按流派分类后,我也想通过专辑的数量排序。可能吗? TIA

+1

的[分组排序一个JS数组]可能的复制(https://stackoverflow.com/questions/16164078/grouped-sorting-on-a- js-array) – Zenoo

+1

标题与这个问题有什么关系? “基于另一个对象进行排序”与“按多个属性排序” – Andreas

+0

[Javascript,如何对多列上的数组进行排序?](https://stackoverflow.com/questions/2784230/javascript-how- do-you-sort-an-array-on-multiple-columns) – Andreas

回答

1
function compare(a, b) { 
// Use toUpperCase() to ignore character casing 
const genreA = a.genre.toUpperCase(); 
const genreB = b.genre.toUpperCase(); 

return genreA.localeCompare(genreB) || a.albums- 
b.albums; 
} 

我将代码缩短到genreA.localeCompare(genreB)。如果它是0,那么流派是平等的,因此我们会根据专辑数量进行比较。

此,如果取0 ...而不是由或运营商提供...

+0

谢谢。有效! –

0

当然,在完成后做什么,你需要与第一阵列做。假设你不想修改你的第一个数组,你可以使用slice创建一个副本。然后你可以按专辑号码排序。让我知道,如果这有助于

const bands = [{ 
 
    genre: 'Rap', 
 
    band: 'Migos', 
 
    albums: 2 
 
    }, 
 
    { 
 
    genre: 'Pop', 
 
    band: 'Coldplay', 
 
    albums: 4, 
 
    awards: 10 
 
    }, 
 
    { 
 
    genre: 'Pop', 
 
    band: 'xxx', 
 
    albums: 4, 
 
    awards: 11 
 
    }, 
 
    { 
 
    genre: 'Pop', 
 
    band: 'yyyy', 
 
    albums: 4, 
 
    awards: 12 
 
    }, 
 
    { 
 
    genre: 'Rock', 
 
    band: 'Breaking zzzz', 
 
    albums: 1 
 
    }, 
 
    { 
 
    genre: 'Rock', 
 
    band: 'Breaking Benjamins', 
 
    albums: 1 
 
    } 
 
]; 
 

 

 
var sortedAlbumNumber = bands.slice(); 
 

 
sortedAlbumNumber.sort((a, b) => a['albums'] - b['albums']); 
 

 
console.log(sortedAlbumNumber);

相关问题