How to Sort an Array of Objects and Keep the Original Index in JavaScript
Assalamu Alaikum,
JavaScript’s sort() method makes it easy to sort an array of objects by a property such as age. But what if you also need to know where each object was in the original array?
Imagine you have a list of people and a separate list of their registration IDs. If you sort the people by age, their positions change. By saving each person’s original index before sorting, you can still match them to the correct registration ID afterward.
Sort objects by age and keep their original indexes
First, use map() to pair each person with their original index. Then sort those pairs by age.
const people = [
{ name: "Alice", age: 32 },
{ name: "Bob", age: 28 },
{ name: "Charlie", age: 45 },
];
const sortedWithIndexes = people
.map((person, originalIndex) => ({ person, originalIndex }))
.sort((a, b) => a.person.age - b.person.age);
console.log(sortedWithIndexes);Output:
[
{ person: { name: "Bob", age: 28 }, originalIndex: 1 },
{ person: { name: "Alice", age: 32 }, originalIndex: 0 },
{ person: { name: "Charlie", age: 45 }, originalIndex: 2 },
]Bob is now first in the sorted array, but his originalIndex is still 1. That value points to his position in people before sorting.
sort() changes the array it runs on. Here, it runs on the new array returned by map(), so people stays in its original order.
Get the sorted objects or their original indexes
Use map() again to extract whichever result you need.
const sortedPeople = sortedWithIndexes.map(({ person }) => person);
const originalIndexes = sortedWithIndexes.map(
({ originalIndex }) => originalIndex
);
console.log(sortedPeople.map(({ name }) => name));
// ["Bob", "Alice", "Charlie"]
console.log(originalIndexes);
// [1, 0, 2]Use the original indexes to reorder related data
Suppose registrationIds follows the same order as people. Use originalIndexes to put the IDs in the same order as the sorted people.
const registrationIds = ["REG-101", "REG-102", "REG-103"];
const sortedRegistrationIds = originalIndexes.map(
(originalIndex) => registrationIds[originalIndex]
);
console.log(sortedRegistrationIds);
// ["REG-102", "REG-101", "REG-103"]Bob moves to the front, and his registration ID, REG-102, moves with him. The same approach works whenever two arrays are aligned by position and you need to apply one array’s sort order to the other.
Happy reading! 🥳 Allah Hafez.
Comments
Join the discussion. Sign in with Google to post; your email is never shown.