我有一个这样的对象:
var list = {
"you": [100,200,300],
"me": [75,4,5,6,8,9],
"foo": [116,345,1,23,56,78],
"bar": [15,34]
};
有什么办法可以通过数组属性的长度sort
来实现此对象?
预期输出:
var res = [[116,345,1,23,56,78],[75,4,5,6,8,9],[100,200,300],[15,34]]
我尝试使用lodash的sortby
函数。
var data = {
"abc": ["20288", "d8f0", "4a5d", "1a8a0"],
"kkl": ["bnb", "lll", "zxc"],
"F17": ["ee547", "42e9"],
"cnv": ["20288", "d8f0", "4a5d", "1a8a0", "jh67"]
}
var res = _.sortBy(data, function(val) {
return parseInt(val.length);
});
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
答案 0 :(得分:1)
如果要将输出作为已排序数组值的数组:
使用 destructuring assignment 通过调用length
从结果数组中获取Object.values
属性,然后按降序对其进行排序。
const data = {
"abc": ["20288", "d8f0", "4a5d", "1a8a0"],
"kkl": ["bnb", "lll", "zxc"],
"F17": ["ee547", "42e9"],
"cnv": ["20288", "d8f0", "4a5d", "1a8a0", "jh67"]
};
const res = Object.values(data).sort(({length:a}, {length:b}) => b - a);
console.log(res);
如果要通过根据数组值的长度重新排列键来对对象本身进行排序。
有什么方法可以根据数组的长度对该对象进行排序 属性?
如果您要按照数组值的length
重新排列原始对象的属性,则我们首先需要按键进行排序,然后创建一个 new >对象,并利用 Array.reduce
对键进行排序。
const data = {
"abc": ["20288", "d8f0", "4a5d", "1a8a0"],
"kkl": ["bnb", "lll", "zxc"],
"F17": ["ee547", "42e9"],
"cnv": ["20288", "d8f0", "4a5d", "1a8a0", "jh67"]
};
//sorting in descending order
const obj = Object.keys(data)
.sort((a, b) => data[b].length - data[a].length )
.reduce((acc, ele) => { acc[ele] = data[ele]; return acc; }, {});
console.log(obj);
答案 1 :(得分:0)
您可以使用 Object.values()
来获取数组中的值,然后基于length
sort
生成2D数组,如下所示:
var data = {
"abc": ["20288", "d8f0", "4a5d", "1a8a0"],
"kkl": ["bnb", "lll", "zxc"],
"F17": ["ee547", "42e9"],
"cnv": ["20288", "d8f0", "4a5d", "1a8a0", "jh67"]
}
const res = Object.values(data).sort((a, b) => b.length - a.length)
console.log(res)