Skip to content
Advertisement

JavaScript array Sort out! Indices problem

Given an array A of non-negative integers of size m. Your task is to sort the array in non-decreasing order and print out the original indices of the new sorted array. e.g.A={4,5,3,7,1}

After sorting the new array becomes A={1,3,4,5,7}.

The required output should be “4 2 0 1 3”

Advertisement

Answer

You need to pair (tuple) the value with the original index. After mapping the tuples, sort by the value and finally map the original (now sorted) indices.

const sortValuesAndGetOriginalIndices = (arr) => arr
  .map((element, index) => [element, index])
  .sort(([v1], [v2]) => v1 - v2)
  .map(([value, index]) => index);

const arr = [4, 5, 3, 7, 1];
const indices = sortValuesAndGetOriginalIndices(arr);

console.log(...indices); // [4, 2, 0, 1, 3]

If you want to return the sorted values and the indicies, you can reduce at the end:

const enhancedSort = (arr) => arr
  .map((element, index) => [element, index])
  .sort(([v1], [v2]) => v1 - v2)
  .reduce(({ values, indices }, [v, i]) =>
    ({
      values: [...values, v],
      indices: [...indices, i]
    }),
    { values: [], indices: [] });

const arr = [4, 5, 3, 7, 1];
const { values, indices } = enhancedSort(arr);

console.log(...values);  // [1, 3, 4, 5, 7]
console.log(...indices); // [4, 2, 0, 1, 3]
.as-console-wrapper { top: 0; max-height: 100% !important; }
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement