Logo

How can I sort this array by the value of the "order" key?

Sorting an array of objects by a particular key is a common scenario in JavaScript. Let’s assume you have an array of objects where each object has an order property, for example:

const items = [ { order: 3, name: "Item 3" }, { order: 1, name: "Item 1" }, { order: 2, name: "Item 2" }, ];

1. Sort in Ascending Order

To sort by the order key (ascending), use the built-in sort() method with a custom comparator:

items.sort((a, b) => a.order - b.order); console.log(items); // Output: // [ // { order: 1, name: "Item 1" }, // { order: 2, name: "Item 2" }, // { order: 3, name: "Item 3" } // ]
  • How It Works: The comparison function (a, b) => a.order - b.order returns a negative number if a.order < b.order, zero if they are the same, and a positive number if a.order > b.order. This is exactly what the sort() method needs to order items correctly.

2. Sort in Descending Order

If you want the highest order value first:

items.sort((a, b) => b.order - a.order); console.log(items); // Output: // [ // { order: 3, name: "Item 3" }, // { order: 2, name: "Item 2" }, // { order: 1, name: "Item 1" } // ]

3. Edge Cases and Best Practices

  1. Missing Keys: If some objects do not have the order key, decide whether to treat those as 0 or place them at the end. For instance:
    items.sort((a, b) => (a.order || 0) - (b.order || 0));
  2. Non-numeric Values: If order can be a string or something else, you need to convert it properly (e.g., parseInt(a.order)).
  3. Stability: JavaScript’s modern engines use a stable sort (Timsort). That means items with equal order values retain their original relative position.

4. Further Learning

If you’re looking to sharpen your JavaScript skills and learn more about data manipulation, check out this course from DesignGurus.io:

Want to go beyond array manipulations and level up your interview preparation? You might also explore:

For live, personalized feedback, consider scheduling a Coding Mock Interview session with ex-FAANG engineers. Also, check out the DesignGurus YouTube Channel for quick video tutorials and deep dives into coding and system design.

Bottom Line: To sort your array by the order key, simply provide a comparator function to sort(), returning the difference of the order properties. This straightforward approach is typically the cleanest and most efficient way to achieve the sort order you need.

CONTRIBUTOR
TechGrind