如何解决基于键的Javascript多级数组排序,但第一个键具有逻辑结构
我有一些特别的问题。我有很多看起来像这样的记录:
let a = [
[[1,2,3],...,b],[[1,5],a]
[[1,2],a],[[1],z]
[[1,3,4],6],d],1],c],]
所以我有一个数组(级别0)和一个数组(级别1),其中包含一些路径部分的数据和数组(级别2)。
现在,我必须按键2对数组级别0进行排序,但是路径仍应构建逻辑树或类似的东西。
因此,如果我按例如最后一个键进行排序,则应该得到如下所示的内容:
let b = [
[[1],z],]
已解决!
我发现最好的和最简单的解决方案随lodash库一起提供。因此,我可以首先按第一列进行排序,然后按选定的键进行排序-这样结构便变得合乎逻辑,并且仅“文件夹中的文件”进行了排序。
代码如下:
let a = [
[[1,]
function TreeStructure(arr,column,dir) {
// Create array duplicate to avoid changes on base array
let a = [...arr];
// flip sort direction based on passed value
// Magic of _Lodash - firstly,sort by the tree ignoring the last item of the tree path,// Then sort by the selected key
a = _.sortBy(a,[
function (item) {
// first - sort by the first array,but with ignoring the last item
// as I mentioned - it's representation of folder tree
// so the last element is the file
const value = item[0].length > 1 ? item[0].slice(0,item[0].length - 1).join("-") : item[0].length;
return value;
},function (item) {
// Then,sort by the selected column
// To prevent errors if some objects or arrays comes in the column I convert them to string
// And to avoid specyfic JS sorting,I convert it to lowercase.
const value = item[column].toString().toLowerCase();
return dir === "asc" ? value : -value;
},]);
return a;
}
解决方法
最短的方法是将String#localeCompare
与通配符连接的所需数组的选项和字符串一起使用。
此方法尊重多于一个数字的值并自然排序。
要对不同的列进行排序,您可以为每种排序方法使用一个函数,并采用具有该列的键的对象,并返回一个函数作为排序的回调。
const
sortPath = col => (a,b) => a[col].join('-').localeCompare(
b[col].join('-'),undefined,{ numeric: true,sensitivity: 'base' }
),sortAlpha = col => ((a,b) => a[col].localeCompare(b[col])),cols = { path: sortPath(0),title: sortAlpha(1) },array = [[[1,2,3],'b'],[[1,5],'a'],2],[[1],'z'],3,4],6],'d'],1],'c']];
array.sort(cols.path);
array.forEach(a => console.log(JSON.stringify(a)));
console.log('----------');
array.sort(cols.title);
array.forEach(a => console.log(JSON.stringify(a)));
.as-console-wrapper { max-height: 100% !important; top: 0; }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。