Pregunta

I have code like this.

var a = JSON.parse(data);
var result = "<table><tr><th></th></tr>";
for (i = 0; i < a.DATA.length; i++) {
  var test = a.DATA[i][0];                      
  result += "<tr'><td>" + test + "</td></tr>";
}
result += "</table>"
$(".show").html(result);

With this code result is like this:

e_file.xlsx,
p_image.png,
test2.docx,
test_folder1,
test_folder2,
text_file.txt

But I need to have folders (test_folder1, test_folder2) and every future folders sorted before other files with suffix.

Thanks.

¿Fue útil?

Solución 2

http://jsfiddle.net/dactivo/tGbYq/

The solution would be a fork on hsz's answer.

The difference is based on the json data you are using. Normally if it was an array of strings as in hsz example, you access directly one by one. With the json you use, you have to first extract the "DATA" part, in this way: alldata["DATA"] and then in the sort function instead of comparing directly to "a" and "b", you have to establish which value to compare, because, every element of the DATA array is another array, that is why we access them with "a[0]" and "b[0]".

To solve this, you can continue to use hsz's solution, but your folder elements have "<dir>" as string in the second value, so you could use this to treat them differently.

Both solutions are OK.

var alldata={ "ERROR": "-", "DATA": [[ "e_file.xlsx", "8759"], ["test2.docx", "23794"], ["test_folder1", "<dir>"], ["test_folder2", "<dir>"], ["p_image.png", "2115194"], ["text_file.txt", "19"]]} 

try{

data=alldata["DATA"];
data.sort(function(a,b)
       {
/*  
         //THIS WOULD BE HSZ'S ANSWER
          var pattern = /\.[a-z]+$/i,
      isADir  = !pattern.test(a[0]),
      isBDir  = !pattern.test(b[0]);

  if (isADir && !isBDir) return -1;
  if (isBDir && !isADir) return 1;

  return a[0] > b[0];
    */       

           if (a[1]=="<dir>" && b[1]!="<dir>") return -1;
            if (a[1]!="<dir>" && b[1]=="<dir>") return 1;


            return a[0] > b[0];

});


    var result = "<table><tr><th></th></tr>";
for (i = 0; i < data.length; i++) {
  var test = data[i][0];                      
  result += "<tr'><td>" + test + "</td></tr>";
}
result += "</table>"

}
catch(e){
alert(e);
}
$(".show").html(result);

Otros consejos

To sort an array with filenames/dirnames you can try with:

var data = ['e_file.xlsx', 'p_image.png', 'test2.docx', 'test_folder1', 'test_folder2', 'text_file.txt'];

var sorted = data.sort(function(a, b){
  var pattern = /\.[a-z]+$/i,
      isADir  = !pattern.test(a),
      isBDir  = !pattern.test(b);

  if (isADir && !isBDir) return -1;
  if (isBDir && !isADir) return 1;

  return a > b;
});

Output:

["test_folder1", "test_folder2", "e_file.xlsx", "p_image.png", "test2.docx", "text_file.txt"]
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top