简体   繁体   中英

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

 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? Or modify the current function and how?

JavaScript objects are typically considered to be an unordered collection of key/value pairs (yes, there are caveats, see this question for details). 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.

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

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.

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