Home > database >  sort and reduce array of objects javascript
sort and reduce array of objects javascript

Time:12-08

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 ?

CodePudding user response:

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

  • Related