I have an object like this:
var list = {
"you": [100,200,300],
"me": [75,4,5,6,8,9],
"foo": [116,345,1,23,56,78],
"bar": [15,34]
};
Is there any way to sort
this object by the length of the array properties?
Expected output:
var res = [[116,345,1,23,56,78],[75,4,5,6,8,9],[100,200,300],[15,34]]
I tried using lodash's sortby
function.
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>
If you want the output as an array of sorted array values:
Use destructuring assignment to get the length
property from the resulting array by calling Object.values
and then sort it in descending order.
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);
If you want to sort the object itself by re-arranging the keys as per the length of array values.
Is there any way to sort this object by the length of the array properties?
If you want to re-arrange the original object properties as per the length
of the array values, then we first need to sort by the keys and then create a new object with the sorted order of the keys utilizing 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);
You can use Object.values()
to get the values in an array and then sort
the resulting 2D array based on the length
like this:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.