JavaScript实现按指定数组顺序排序对象数组的问题
JavaScript: Sort Object Array Based on a Predefined Order Array
Got it, let's solve this problem where we need to sort the obj array according to the order of abbreviations specified in the arr array. Here's a clean and efficient approach:
Step-by-Step Solution
First, we'll create a lookup map to quickly get the position of each abbreviation from the arr array—this avoids repeated indexOf calls which can be slow with large arrays. Then we'll use this map to sort the obj array.
Full Code Implementation
var arr = ['VBH', 'KTL', 'PVC', 'IF & AF', 'BC', 'CC&HC', 'UBS', 'FAD&DVD']; var obj = [ {"materialTypeID":9,"name":"","abbreviation":"UBS","count":1,"duns":0,"plantId":0}, {"materialTypeID":18,"name":null,"abbreviation":"PVC","count":1,"duns":0,"plantId":0}, {"materialTypeID":7,"name":"","abbreviation":"FAD&DVD","count":4,"duns":0,"plantId":0} ]; // Create a map to store abbreviation -> its index in arr const orderLookup = arr.reduce((acc, curr, idx) => { acc[curr] = idx; return acc; }, {}); // Sort the obj array without modifying the original (use obj.sort() if you want to mutate) const sortedObj = [...obj].sort((a, b) => { // Compare the indices from our lookup map return orderLookup[a.abbreviation] - orderLookup[b.abbreviation]; }); console.log(sortedObj);
How It Works
- Lookup Map Creation: The
reducemethod builds an object where each key is an abbreviation fromarr, and the value is its position (index) inarr. This lets us get the order position in O(1) time instead of O(n) withindexOf. - Sorting: The
sortmethod compares two objects by looking up their abbreviation's index in the map. Subtracting the indices ensures that objects with smaller indices (earlier inarr) come first. - Immutability: Using
[...obj]creates a copy of the original array before sorting, so we don't modify the originalobjarray. If you don't mind mutating the original, you can skip the spread and just useobj.sort(...).
Handling Edge Cases
- If an object in
objhas an abbreviation that's not inarr,orderLookup[abbreviation]will beundefined. In this case, those objects will be grouped at the end of the sorted array (sinceundefined - numberisNaN, andsorttreatsNaNas equivalent when comparing). - If you want to handle missing abbreviations differently (e.g., put them at the start), you can adjust the sort function:
.sort((a, b) => { const idxA = orderLookup[a.abbreviation] ?? Infinity; // Push missing entries to end const idxB = orderLookup[b.abbreviation] ?? Infinity; return idxA - idxB; });
Output
Running the code will give you exactly the sorted array you expected:
[ {"materialTypeID":18,"name":null,"abbreviation":"PVC","count":1,"duns":0,"plantId":0}, {"materialTypeID":9,"name":"","abbreviation":"UBS","count":1,"duns":0,"plantId":0}, {"materialTypeID":7,"name":"","abbreviation":"FAD&DVD","count":4,"duns":0,"plantId":0} ]
内容的提问来源于stack exchange,提问作者Himani
相关产品推荐
相关产品推荐

