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

如何按另一对象数组的ID顺序对目标对象数组排序

Solution: Sort array by arraySorted's ID order

Here's a straightforward way to achieve this using native JavaScript, leveraging a position map for efficient sorting:

Step-by-Step Explanation

  1. Create a position lookup map: First, we build an object that maps each ID from arraySorted to its index in that array. This lets us quickly look up where each ID should appear in the final sorted array.
  2. Sort the original array: Use the sort() method on a copy of array (to avoid mutating the original), comparing elements based on their positions from the lookup map.

Code Implementation

const array = [ {id: 5, name: "Helen", age: 20}, {id: 15, name: "Lucy", age: 30}, {id:7, name: "Carlos", age: 1} ];
const arraySorted = [ {id: 15, name: "Lucy", age: 2}, {id: 5, name: "Lara", age: 11}, {id:7, name: "Carlos", age: 10} ];

// Build a map of ID to its index in arraySorted
const idPositionMap = arraySorted.reduce((map, item, index) => {
  map[item.id] = index;
  return map;
}, {});

// Sort array using the position map (creates a new array to avoid mutating original)
const sortedArray = [...array].sort((a, b) => {
  return idPositionMap[a.id] - idPositionMap[b.id];
});

console.log(sortedArray);
// Output: [
//   {id: 15, name: "Lucy", age: 30},
//   {id: 5, name: "Helen", age: 20},
//   {id:7, name: "Carlos", age: 1}
// ]

Key Notes

  • Immutability: Using [...array] creates a shallow copy of the original array before sorting, so the original array remains unchanged. If you don't mind mutating the original, you can skip the spread and just do array.sort(...).
  • Efficiency: Building the map is O(n), and sorting is O(m log m) where m is the length of array. Since we know all IDs match between the two arrays, we don't need to handle edge cases where an ID isn't found in the map.

内容的提问来源于stack exchange,提问作者user3808307

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:26:08