alexdagee
alexdagee

Reputation: 25

javascript sort multidimensional array

so i have a multidimensional array in javascript (can t use php) and want to sort it by the variables "filename" and "size". I got the arrays from an other website (dynamic data via xml). my var's look like this (extracted from much other code, ask if u need the other code):

    var id = new Array();
var filename = new Array();
var url = new Array();
var size = new Array();
var creationDate = new Array();
var mimetype = new Array();
var thumbnailAvailable = new Array();

how can i sort them? do i need an array over these arrays?

thanks for your help!

Upvotes: 0

Views: 170

Answers (1)

MT0
MT0

Reputation: 167811

var id = [ 'bId', 'aId', 'cId', 'eId', 'dId', 'cId' ];
var filename = [ 'b', 'a', 'c', 'e', 'd', 'c' ];
var url = [ 'aa', 'bb', 'ccx', 'ee', 'dd', 'ccy' ];
var size = [ 1, 1, 2, 1, 1, 1 ];
var creationDate = [ 0, 1, 2, 3, 4, 5 ];
var mimetype = [ 'x', 'y', 'x', 'y', 'x', 'x' ];
var thumbnailAvailable = [ false, false, false, false, true, false ];

var fileData = [];
for ( var i = 0; i < id.length; ++i )
{
    fileData.push( {
                    id: id[i],
                    filename: filename[i],
                    url: url[i],
                    size: size[i],
                    creationDate: creationDate[i],
                    mimetype: mimetype[i],
                    thumbnailAvailable: thumbnailAvailable[i]
                   } );
}
fileData.sort( function(a,b){
    if ( a.filename < b.filename )
        return -1;
    if ( a.filename > b.filename )
        return 1;
    return a.size - b.size;
} );

for (var i = 0; i < fileData.length; ++i )
    alert( fileData[i].filename + " - " + fileData[i].size );

JSFiddle

Upvotes: 1

Related Questions