简体   繁体   English

排序和减少对象数组 javascript

[英]sort and reduce array of objects javascript

i have an array of objects like this:我有一组这样的对象:

 const array = [ { type: "sale", product: "aaa" }, { type: "rent", product: "bbb" }, { type: "sale", product: "ccc" }];

and i use this function to summarize the array我用这个 function 来总结数组

 array.reduce((acc, o) => ((acc[o.type] = (acc[o.type] || 0) + 1), acc),{})

result:结果:

 {sale: 2, rent: 1}

but i wanna sort this summary object Ascending like this {rent: 1,sale: 2} Do I need to use another function?但我想对这个摘要进行排序 object 像这样升序{rent: 1,sale: 2}我需要使用另一个 function 吗? Or modify the current function and how?或者修改当前的function又如何呢?

JavaScript objects are typically considered to be an unordered collection of key/value pairs (yes, there are caveats, see this question for details). JavaScript 对象通常被认为是键/值对的无序集合(是的,有一些注意事项,有关详细信息,请参阅此问题)。 If you want an ordered result, you should use an array instead.如果你想要一个有序的结果,你应该使用一个数组来代替。

That being said, for objects with string keys, the keys are ordered in insertion order, so it's sufficient to convert your object to an array, sort that as desired, and convert it back to an object again.也就是说,对于具有字符串键的对象,键按插入顺序排序,因此将 object 转换为数组,根据需要对其进行排序,然后再次将其转换回 object 就足够了。

 const array = [ { type: "sale", product: "aaa" }, { type: "rent", product: "bbb" }, { type: "sale", product: "ccc" } ]; const raw = array.reduce((a, v) => (a[v.type] = (a[v.type] || 0) + 1, a), {}); const sorted = Object.fromEntries( Object.entries(raw).sort(([k1, v1], [k2, v2]) => v1 - v2) ); console.log(sorted);

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

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