如何在JavaScript中基于多条件对对象数组进行排序?
First, let's restate your sample array for clarity:
const data = [ { id: 34, users: [{ name: 'Lisa', age: 23 }, { name: 'Steven', age: 24 }] }, { id: 35, users: [{ name: 'John', age: 23 }, { name: 'Steven', age: 24 }, { name: 'Charlie', age: 24 }] }, { id: 36, users: [{ name: 'Lisa', age: 23 }, { name: 'John', age: 24 }, { name: 'Homer', age: 24 }, { name: 'Charlie', age: 24 }] }, { id: 37, users: [{ name: 'Lisa', age: 23 }, { name: 'John', age: 24 }] } ];
To sort this array with multiple conditions, you'll use JavaScript's Array.sort() method with a custom comparator function. The core idea is to check your conditions in priority order: if the first condition differentiates two items, return the result immediately; if not, move to the next condition, and so on.
Example: Sort by Number of Users, then by ID
Let’s use a common set of priority conditions to demonstrate:
- Primary: Sort by the number of users in each group (ascending: fewer users first)
- Secondary: If two groups have the same number of users, sort by the
id(ascending: smaller ID first)
Here’s the implementation:
// Create a copy of the array to avoid mutating the original data const sortedData = [...data].sort((a, b) => { // First condition: compare user count const userCountDiff = a.users.length - b.users.length; if (userCountDiff !== 0) { return userCountDiff; // Return non-zero value to sort by this condition } // Second condition: fall back to ID comparison if user counts are equal return a.id - b.id; }); console.log(sortedData);
How It Works
- We spread the original array (
[...data]) becausesort()modifies arrays in place—this preserves your original data. - The comparator function takes two items
aandb:- First, we calculate the difference in user counts. A negative value means
acomes beforeb; positive meansbcomes beforea. - If user counts are identical, we use numeric subtraction on the
idvalues to sort in ascending order.
- First, we calculate the difference in user counts. A negative value means
Adding More Conditions
If you want to layer in another rule (e.g., sort by the first user’s name alphabetically when counts and IDs match), extend the comparator like this:
const sortedData = [...data].sort((a, b) => { // Primary: user count const userCountDiff = a.users.length - b.users.length; if (userCountDiff !== 0) return userCountDiff; // Secondary: ID const idDiff = a.id - b.id; if (idDiff !== 0) return idDiff; // Tertiary: first user's name (alphabetical order) return a.users[0].name.localeCompare(b.users[0].name); });
Customizing for Your Needs
You can tweak this logic to fit any conditions:
- For descending order, reverse the subtraction (e.g.,
b.users.length - a.users.lengthto prioritize groups with more users). - For string comparisons, use
localeCompare()(it handles accented characters and case sensitivity better than direct string subtraction). - For boolean checks (e.g., "does this group include 'Steven'?"), return
-1or1based on the result of the check.
This approach keeps your sorting logic clean, readable, and easy to adjust as your requirements change.
内容的提问来源于stack exchange,提问作者Hommer Smith

