简体   繁体   English

按数组属性的长度对 JavaScript 对象进行排序

[英]Sort JavaScript object by length of array properties

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?有没有办法按数组属性的长度sort这个对象进行sort

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.我尝试使用 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>

  1. 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.通过调用Object.values使用解构赋值从结果数组中获取length属性,然后按降序对其进行排序。

 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);


  1. 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 .如果您想根据数组值的length重新排列原始对象属性,那么我们首先需要按键排序,然后使用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:您可以使用Object.values()获取数组中的值,然后根据length对生成的二维数组进行sort ,如下所示:

 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM