ArticleZip > Javascript Sort Array And Return An Array Of Indices That Indicates The Position Of The Sorted Elements With Respect To The Original Elements

Javascript Sort Array And Return An Array Of Indices That Indicates The Position Of The Sorted Elements With Respect To The Original Elements

Sorting arrays in JavaScript is a handy task when working with data, and sometimes, you might want to retain the original order of elements before sorting. In this guide, we'll walk through how to sort an array and then return an array of indices that indicates the position of the sorted elements concerning the original elements.

Let's dive into the steps to achieve this in JavaScript. First, we need to create a sample array to work with:

Javascript

const originalArray = [5, 2, 8, 1, 9];

To sort this array and get the sorted elements, we can use the `slice()` method to avoid modifying the original array:

Javascript

const sortedArray = originalArray.slice().sort((a, b) => a - b);

Now that we have the sorted array, let's generate an array of indices to map the sorted elements back to their original locations. We can leverage the `map()` method along with `indexOf()` to achieve this:

Javascript

const indicesArray = originalArray.map(element => sortedArray.indexOf(element));

By using the `indexOf()` method on the sorted array, we can find the positions of each element from the original array in the sorted array. The `indicesArray` will now hold the indices that tell us where each element from the original array sits in the sorted array.

Let's put it all together:

Javascript

const originalArray = [5, 2, 8, 1, 9];
const sortedArray = originalArray.slice().sort((a, b) => a - b);
const indicesArray = originalArray.map(element => sortedArray.indexOf(element));

console.log("Original Array:", originalArray);
console.log("Sorted Array:", sortedArray);
console.log("Indices Array:", indicesArray);

When you run this code snippet, you'll see the original array, the sorted array, and the array of indices indicating the position of the sorted elements concerning the original elements.

This technique allows you to sort an array in JavaScript while keeping track of the original order of elements. It can be particularly useful when you need to sort data but still maintain a reference to the original positions within the array.

Now that you've mastered sorting arrays and returning an array of indices in JavaScript, you can efficiently manage your data structures with ease. Feel free to experiment with different arrays and see how this method can benefit your projects!

×