在编写 JavaScript 排序函数时遇到问题,该函数可以让我执行以下操作:
更新:这是 Node.js 的 javascript
我有一堆文件和文件夹作为 JSON 对象,具有以下属性
[
{"name":"Folder B","isFolder":true},
{"name":"File A","isFolder":false},
{"name":"Folder A","isFolder":true},
{"name":"File B","isFolder":false}
]
我想对此数组进行排序,以便文件夹分组在顶部并按字母顺序排序,然后文件按字母顺序排序
[
{"name":"Folder A","isFolder":true},
{"name":"Folder B","isFolder":true},
{"name":"File A","isFolder":false},
{"name":"File B","isFolder":false}
]
经过对 stackoverflow 的大量研究,我想出了这个,但它只是将文件夹分组在顶部,并且不按名称排序..想法?
array.sort(function(a,b){
return (b.isFolder-a.isFolder) || (b.name - a.name);
}));
最佳答案
从一个字符串中减去另一个字符串将始终得到“NaN”,而应使用 localeCompare()。
array.sort(function(a,b){
return (b.isFolder-a.isFolder) || (a.name.toString().localeCompare(b.name));
});
关于带有分组功能的 JavaScript 排序功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27177658/