0

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!

4
  • 1
    Well what you have there is not a "multi-dimensional array". It is a list of seven separate, independent arrays. Commented Nov 30, 2013 at 23:19
  • You want to merge them by index and sort by size and filename values? Commented Nov 30, 2013 at 23:20
  • when you extract xml with php, no reason you can't sort there, and output as json Commented Nov 30, 2013 at 23:40
  • ok. should i put the var's together in one array? Commented Dec 1, 2013 at 10:49

1 Answer 1

1
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

Sign up to request clarification or add additional context in comments.

1 Comment

As written it sorts highest to lowest, but that's easily corrected if you don't want that--just change the -1 to 1 and vice versa, and then return a.size - b.size. It DID sort, though--and that makes it correct in my view. By what criteria did you decide it doesn't work?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.