0

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 ?

0

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.