How do you sort an array on multiple columns?

前端 未结 16 1344
面向向阳花
面向向阳花 2020-11-22 13:02

I have a multidimensional array. The primary array is an array of

[publicationID][publication_name][ownderID][owner_name] 

What I am tryin

16条回答
  •  無奈伤痛
    2020-11-22 13:41

    I suggest to use a built in comparer and chain the wanted sort order with logical or ||.

    function customSort(a, b) {
        return a[3].localeCompare(b[3]) || a[1].localeCompare(b[1]);
    }
    

    Working example:

    var array = [
        [0, 'Aluminium', 0, 'Francis'],
        [1, 'Argon', 1, 'Ada'],
        [2, 'Brom', 2, 'John'],
        [3, 'Cadmium', 3, 'Marie'],
        [4, 'Fluor', 3, 'Marie'],
        [5, 'Gold', 1, 'Ada'],
        [6, 'Kupfer', 4, 'Ines'],
        [7, 'Krypton', 4, 'Joe'],
        [8, 'Sauerstoff', 3, 'Marie'],
        [9, 'Zink', 5, 'Max']
    ];
    
    array.sort(function (a, b) {
        return a[3].localeCompare(b[3]) || a[1].localeCompare(b[1]);
    });
    
    document.write('
    ');
    array.forEach(function (a) {
        document.write(JSON.stringify(a) + '
    '); });

提交回复
热议问题