Javascript: Sort array and return an array of indicies that indicates the position of the sorted elements with respect to the original elements

javascript sort multidimensional array alphabetically
javascript sort array of objects
javascript sort array of objects by key
javascript array sort performance
javascript sort two dimensional array numerically
javascript sort by index
javascript sort return
javascript sort array of numbers

Suppose I have a Javascript array, like so:

var test = ['b', 'c', 'd', 'a'];

I want to sort the array. Obviously, I can just do this to sort the array:

test.sort(); //Now test is ['a', 'b', 'c', 'd']

But what I really want is an array of indices that indicates the position of the sorted elements with respect to the original elements. I'm not quite sure how to phrase this, so maybe that is why I am having trouble figuring out how to do it.

If such a method was called sortIndices(), then what I would want is:

var indices = test.sortIndices();
//At this point, I want indices to be [3, 0, 1, 2].

'a' was at position 3, 'b' was at 0, 'c' was at 1 and 'd' was a 2 in the original array. Hence, [3, 0, 1, 2].

One solution would be to sort a copy of the array, and then cycle through the sorted array and find the position of each element in the original array. But, that feels clunky.

Is there an existing method that does what I want? If not, how would you go about writing a method that does this?

var test = ['b', 'c', 'd', 'a'];
var test_with_index = [];
for (var i in test) {
    test_with_index.push([test[i], i]);
test_with_index.sort(function(left, right) {
  return left[0] < right[0] ? -1 : 1;
var indexes = [];
test = [];
for (var j in test_with_index) {


You guys are right about for .. in. That will break if anybody munges the array prototype, which I observe annoyingly often. Here it is with that fixed, and wrapped up in a more usable function.

function sortWithIndeces(toSort) {
  for (var i = 0; i < toSort.length; i++) {
    toSort[i] = [toSort[i], i];
  toSort.sort(function(left, right) {
    return left[0] < right[0] ? -1 : 1;
  toSort.sortIndices = [];
  for (var j = 0; j < toSort.length; j++) {
    toSort[j] = toSort[j][0];
  return toSort;

var test = ['b', 'c', 'd', 'a'];

Position of an element after stable sort, That will break if anybody munges the array prototype, which I observe using es6 (generating a 0->N-1 index array and sorting it based on the input values). My solution is to create a typed array of indices, then use a comparison function to sort these indices based on the to-be-sorted array. Then we can use the sorted indices to either sort the original array or create a sorted copy in a single pass. If that's confusing, think of it this way: where you would normally pass a comparison function like:

I would just fill an array with numbers 0..n-1, and sort that with a compare function.

var test = ['b', 'c', 'd', 'a'];
var len = test.length;
var indices = new Array(len);
for (var i = 0; i < len; ++i) indices[i] = i;
indices.sort(function (a, b) { return test[a] < test[b] ? -1 : test[a] > test[b] ? 1 : 0; });

Reorder an array according to given indexes, Input : arr[] = [3, 4, 3, 5, 2, 3, 4, 3, 1, 5], index = 5 Output : 4 Element initial index – 5 (third 3) After sorting array by stable sorting algorithm, we get array as shown  41 Javascript: Sort array and return an array of indicies that indicates the position of the sorted elements with respect to the original elements Sep 16 '10 20 Displaying objects in IE Developer Tools console Jan 23 '13

Dave Aaron Smith is correct, however I think it is interesting to use Array map() here.

var test = ['b', 'c', 'd', 'a'];
// make list with indices and values
indexedTest =,i){return {ind: i, val: e}});
// sort index/value couples, based on values
indexedTest.sort(function(x, y){return x.val > y.val ? 1 : x.val == y.val ? 0 : -1});
// make list keeping only indices
indices ={return e.ind});

Sophisticated Sorting in JavaScript, Given two integer arrays of same size, “arr[]” and “index[]”, reorder elements in “​arr[]” C++ program to sort an array according to given cout << "\nModified Index array is: \n" ;. for ( int i=0; i<n; i++). cout << index[i] << " " ;. return 0;. } Generate original array from an array that store the counts of greater elements on right  Partition the input array such that all odd elements are moved to left and all even elements on right. This step takes O(n). This step takes O(n). Once the array is partitioned, sort left and right parts individually.

You can accomplish this with a single line using es6 (generating a 0->N-1 index array and sorting it based on the input values).

var test = ['b', 'c', 'd', 'a']

var result = Array.from(Array(test.length).keys())
                  .sort((a, b) => test[a] < test[b] ? -1 : (test[b] < test[a]) | 0)

How to find the index where a number belongs in an array in , If sort() is called with no argument, then the array is sorted if the function returns zero, leave a and b unchanged with respect to each other The JavaScript specification refers to the first sort-condition as sort b to a lower index than a . You can load external data, create elements for test-rendering,  At this point, it might appear that sorting elements of an ArrayList is very simple.We only need to call theCollections.sort() method passing the ArrayList object whose elements needs to be sorted

This is a more idiomatic ES6 version of clerbois' answer, see his/hers for comments:

return, ind) => {return {ind, val}})
           .sort((a, b) => {return a.val > b.val ? 1 : a.val == b.val ? 0 : -1 })
           .map((obj) => obj.ind);

Array.prototype.sort(), Sorting is a very important concept when writing algorithms. We have to sort an array of numbers from least to greatest and find returns the first index at which an element is present in an array, or a -1 Otherwise, it returns -1, indicating no element passed the test. JavaScript Promise What is GitHub? Count elements less than or equal to a given value in a sorted rotated array; Count of smaller or equal elements in sorted array; Noble integers in an array (count of greater elements is equal to value) Number of ways to select equal sized subarrays from two arrays having atleast K equal pairs of elements; Count of operations to make all

Understanding the Sort Method of Arrays, The sort() method sorts the elements of an array in place and returns the sorted array. If compareFunction(a, b) returns less than 0, sort a to an index lower than with respect to each other, but sorted with respect to all different elements. four arrays and displays the original array, then the sorted arrays. If A is complex, then by default, sort sorts the elements by magnitude. If more than one element has equal magnitude, then the elements are sorted by phase angle on the interval (−π, π]. If A is a cell array of character vectors or a string array, then sort(A) sorts the elements according to the code order for the UTF-16 character encoding

JavaScript Array sort: Sorting Array Elements, The JavaScript array sort() is used to sort array elements. The two arguments are taken as from array on index [0,1] , [1,2] … The sorting of elements is based on the return value of compareFunction for each pair of comparison. returns a number indicating whether a reference string comes before or  JavaScript's sorting mechanism is a model of simplicity, yet bubbling under the surface is some incredibly flexible and powerful functionality. Using sort it's possible to organise arrays, not

template function, Besides returning the sorted array, the sort() method changes the positions of the elements in the original array. By default, the sort() method sorts the array elements in ascending order with the smallest value first and If compare(a,b) is greater than zero, the sort() method sort b to a lower index than a , i.e., b will come first. direction can also be a cell array whose elements are 'ascend' and 'descend', where each element corresponds to the specified variables, row names, or row times being sorted on. example tblB = sortrows( ___ , Name,Value ) specifies additional parameters for sorting rows of a table or timetable.

  • +1 but I think you better not use a for .. in loop on an array.
  • That is a good idea. I will give that a try. (I will accept once I get it working.)
  • @Tomalak: I agree with you about for .. in. I have run into a lot of problems with it.
  • Using for-in with an Array is almost always a very bad idea.
  • This is great, and it can be even a little better (make the sort stable!) by comparing the indices (a and b) if the values are equal. I.e., change ... test[a] > test[b] ? 1 : 0 to ... test[a] > test[b] ? 1 : a < b ? -1 : 1, as per:…
  • Also see this great answer that provides a (admittedly less performant) way to populate the array in one line. Spoiler: let indices = [...Array(test.length).keys()];.
  • Why not use .call instead of .apply?
  • because it's later in the alphabet :) no real reason to be honest, probably makes more sense to use call in this case, as then an array doesn't need to be created each time. Will update now