如何按另一对象数组的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
- Create a position lookup map: First, we build an object that maps each ID from
arraySortedto its index in that array. This lets us quickly look up where each ID should appear in the final sorted array. - Sort the original array: Use the
sort()method on a copy ofarray(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 originalarrayremains unchanged. If you don't mind mutating the original, you can skip the spread and just doarray.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
相关产品推荐
相关产品推荐

