You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 reduce method builds an object where each key is an abbreviation from arr, and the value is its position (index) in arr. This lets us get the order position in O(1) time instead of O(n) with indexOf.
  • Sorting: The sort method compares two objects by looking up their abbreviation's index in the map. Subtracting the indices ensures that objects with smaller indices (earlier in arr) come first.
  • Immutability: Using [...obj] creates a copy of the original array before sorting, so we don't modify the original obj array. If you don't mind mutating the original, you can skip the spread and just use obj.sort(...).

Handling Edge Cases

  • If an object in obj has an abbreviation that's not in arr, orderLookup[abbreviation] will be undefined. In this case, those objects will be grouped at the end of the sorted array (since undefined - number is NaN, and sort treats NaN as 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:41:20