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 ifa.order < b.order
, zero if they are the same, and a positive number ifa.order > b.order
. This is exactly what thesort()
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
- Missing Keys: If some objects do not have the
order
key, decide whether to treat those as0
or place them at the end. For instance:items.sort((a, b) => (a.order || 0) - (b.order || 0));
- Non-numeric Values: If
order
can be a string or something else, you need to convert it properly (e.g.,parseInt(a.order)
). - 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:
- Grokking JavaScript Fundamentals – A deep dive into core JavaScript concepts, modern features (like arrow functions and ES6+), and coding best practices.
Want to go beyond array manipulations and level up your interview preparation? You might also explore:
- Grokking the Coding Interview: Patterns for Coding Questions – Learn to identify and apply recurring coding patterns in interviews, saving you time and boosting accuracy.
- Grokking Data Structures & Algorithms for Coding Interviews – Master arrays, linked lists, trees, and more to confidently tackle challenging problems.
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.