Home > Software design >  JavaScript array Sort out! Indices problem
JavaScript array Sort out! Indices problem

Time:06-21

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"

CodePudding user response:

You could get the indices and sort only the indices array by the values of the given data.

const
    array = [4, 5, 3, 7, 1],
    indices = [...array.keys()].sort((a, b) => array[a] - array[b]);

console.log(...indices);

CodePudding user response:

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; }

  • Related