I have the following code:

```
//data_r is an array with values
var i = 0;
var sort_order = new Array();
data_r.sort(function (a,b) {
var res = a[0] - b[0];
sort_order[i] = res;
i++;
return res;
});
```

In the end, the sort_order array contains the actions performed when we sorted items. If I want to sort a second array exactly the same way as the first then I can do the following:

```
//data_x is an array with values
var i = 0;
data_x.sort(function (a,b) {
i++;
return sort_order[i-1];
});
```

Now the data_x array is sorted exactly the same way as the data_r array.

**The question is, how can I undo sort on the data_r array?**

The following code is incorrect:

```
var unsort = new Array();
for(var i = 0; i < data_r.length; i++)
unsort[i] = sort_order[i]*(-1);//-1 so we perfom the oposite action
```

Why, please?

**EDIT:**

I can't make a copy of the array.

I have array #1. I sort it.

**Then** I receive array #2 **but the array is sorted** based on array #1.

I need to reverse the sorting on array #2.

**EDIT 2:**

array #1 = {9, 5, 3, 0, 2}

I sort the array #1:

array #1 = {0, 2, 3, 5, 9}

NOW i receive array #2 sorted based on array #1:

array #2 = {"home", "car", "train", "pc", "mouse"}

I need to make array #2 like this:

array #2 = {"mouse, "pc", "train", "home", "car"}

**solved**: http://jsfiddle.net/fQm3a/

Your premise here is flawed.

In the end, the sort_order array contains the actions performed when we sorted items.

No, it doesn't; it contains a log of the comparisons performed by the Javascript `Array.sort`

function. The actions it took in response to those comparison results are private to it.

If I want to sort a second array exactly the same way as the first then I can do the following:

This is not guaranteed to work. Even if the two arrays are the same size, `Array.sort`

may not always compare the same elements in the same order each time it's called - it's possible that it's using a randomized algorithm, that it performs comparisons based on other data that are internal to the interpreter, or that it switches between multiple entirely different sort algorithms under some circumstances.

While this code may work for you, right now, in your current web browser, it is likely to fail in surprising ways in other circumstances (possibly in future browsers). Do not use this technique in production code.

The question is, how can i unsort the data_r array?

Make a copy of the array before you sort it.

The sort function just returns a number which can be positive,zero, or negative telling it if the current element goes before,has same weight, or goes after the element it is comparing it too. I would imagine your sort order array is longer than your data_r array because of the number of comparisons you make. I would just make a copy of data_r before you sort it and then set data_r equal to that array when you want it unsorted.

Storing res[i] = a - b is like journaling the sort() algorithm - but what if it used a random pivot? This code is inherently unreliable unless you write sort() yourself. It's also inefficient.

A better approach, one that will solve both your needs, is to create an array of indices and sort that. This is trivial to invert. Then you can implement a permute function that takes an array of indices, and it achieves a sort or unsort, depending on the input.

If x is from 0:n-1, create an array sort_i of same size, then initialize each sort_i[i] = i.

```
for(var i = 0; i < n; i++)
sort_i[i] = i;
```

Then

```
sort_i.sort(function (a,b) { return x[a] - x[b]; });
```

Now you have the indices. To apply to x:

```
for(var i = 0; i < n; i++)
sort_x[i] = x[sort_i[i]];
```

To unsort it, first invert the indices

```
for(var i = 0; i < n; i++)
unsort_i[sort_i[i]] = i;
```

Then apply the indices. Exercise left to question asker.

This approach of sorting an array of integer indices is needed when you don't want to move the original elements around in memory (maybe they are big objects), and many other circumstances. Basically you are sorting pointers. The result is an index to the data, and a reverse index.

See @duskwuff's answer on why your approach doesn't work.

Instead, just introduce a mapping between the original data and the sorted data.

```
{0:2, 1:3, 2:1, 3:0}
```

Which means the first element became the third, the second became the last and so on. Below we'll use an array instead of an object.

Why does this map help? You can sort it *like* another dataset by just using the indizes in it as pointers to the data you're going to compare. And you can apply the mapping easily on other datasets. And you can even reverse that mapping very easily. See it in the code:

```
// data_r, data_x are arrays with values
var l = data_r.length;
var sort_order = new Array(l);
for (var i=0; i<l; i++) sort_order[i] = i; // initialised as 1-1 mapping
// change the sort_order first:
sort_order.sort(function (a,b) {
// a and b being indices
return data_r[a] - data_r[b];
});
```

```
// Making a new, sorted array
var data_x_sorted = new Array(l);
for (var i=0; i<l; i++)
data_x_sorted[ sort_order[i] ] = data_x[i]; // put it to sorted position
```

If you want to sort the `data_x`

array itself, just use the "apply" algorithm which I showed for `data_r`

.

The question is, how can I undo sort on the

`data_r`

array?

Either don't sort it at all, and just make a copy of it which gets sorted (or do nothing at all).

Or use the `sort_order`

to reverse it. You just would need to swap `i`

and `newIndex`

(`sortOrder[i]`

) everywhere. Example for building a new, "unsorted" (old-order) array:

```
var unsorted = new Array(l);
for (var i=0; i<l; i++)
unsorted[i] = data_r[ sort_order[i] ]; // take it from its new position
```

If you have a lot of these arrays to maintain, it might be as well to convert array1 into an array of objects, each one containing the value and its original position in the array. This keeps everything together in one array.

```
var array1 = [9, 5, 3, 0, 2];
var array2 = ["home", "car", "train", "pc", "mouse"];
var sort = function(array){
var indexed_objects = array.map(function(value, index){
return {index: index, value: value};
});
indexed_objects.sort(function(a,b){
return a.value > b.value;
});
return indexed_objects;
};
var sorted1 = sort(array1);
sorted1; // [{index: 3, value:0}, {index: 4, value: 2}, ...]
```

And now, given an array of sorted objects, we can write a function to unsort any other array accordingly:

```
var unsort = function(array, sorted_objects){
var unsorted = [];
sorted_objects.forEach(function(item, index){
unsorted[item.index] = array[index];
});
return unsorted;
};
var array2_unsorted = unsort(array2, sorted1);
array2_unsorted; // ["mouse", "pc", "train", "home", "car"]
```

Similar Questions

I have an array which looks like this: array[0]: 6 8 array[1]: 12 9 6 array[2]: 33 32 5 array[3]: 8 6 What I want to do is to sort this array that it looks like this: array[0]: 6 8 array[1]: 6 9 12 a

I have an array in javascript that contains the following: [Value 1, Value 5. Value 10, Value 11]; How would I go about sort this array so that it does not appear as follows: [Value 1, V

I was helping somebody out with his JavaScript code and my eyes were caught by a section that looked like that: function randOrd(){ return (Math.round(Math.random())-0.5); } coords.sort(randOrd); aler

I have an array as follows var arry = [ [1, Convention Hall, Mumbai, 10, XYZ Company], [2, Auditorium, Delhi, 10, ABC Company], [3, CenterHall, Bangalore, 10, ZZZ Company], .... ] I

I apologize if this has been asked here - I've hunted around here and in the Tentative NumPy Tutorial for an answer. I have 2 numpy arrays. The first array is similar to: 1 0 0 0 0 2 0 0 0 0 3 0 0 0 0

I have two arrays. I should do a normal sort on one (descending or ascending) and sort the other according to how the first array is sorted. This is because each element in the first array has a relat

I am trying to sort an array of objects with each object containing var recent = [{id: 123,age :12,start: 10/17/13 13:07} , {id: 13,age :62,start: 07/30/13 16:30}]; Date format is: mm/dd/yy

I have a JavaScript array like this var myData=['237','124','255','124','366','255']; I need the array elements to be unique and sorted: myData[0]='124'; myData[1]='237'; myData[2]='255'; myData[3]=

I am new to Jquery and Javascript. Can someone please help me with Jquery sorting based on number of occurrence(count) in array. I tried various sorting methods but none of them worked. I have an arr

I'm trying to sort an array of objects in javascipt. Sort order itself depends on two factors: object's properties and a value of a single external variable. I know that I can use array.sort(sortFunct

I have a reference array which contains all possible elements and is sorted in custom order different than alphanumeric sorting. For example, @ref_array = ('one','two','three','four','five','six'); N

Let's suppose I wanted a sort function that returns a sorted copy of the inputted array. I naively tried this function sort(arr) { return arr.sort(); } and I tested it with this, which shows that my

I need to have all the values of checked checkboxes sorted with commas in javascript, so I can send the to a form sending php script. The javascript: var services = []; $('#field-services:checked').e

[This is an interview question. I couldn't find a duplicate.] An array contains two sub- sorted arrays. Give an inplace algorithm to sort two sub arrays. for ex: I/P: 1 4 5 7 8 9 2 3 6 10 11 O/P: 1 2

I am trying to sort an array so that all the zeros are at the end. However, I don't want the list to be numerically sorted, all the numbers above zero should stay in the same order. Here's what I've g

I have to write a C++ code that finds the median and mode of an array. I'm told that it's much easier to find the mode of an array AFTER the numbers have been sorted. I sorted the function but still c

I want to sort two already sorted arrays into one. I am using merge sort for this purpose. Error:: IndexError: list index out of range I have tried checking out this manually and I couldnt find out of

I have a sorted JavaScript array, and want to insert one more item into the array such the resulting array remains sorted. I could certainly implement a simple quicksort-style insertion function: var

I want to create an almost sorted array, as efficiently as possible (to explore effect of random subtle variations in a list, I expect to call this routine a lot). I have Ruby code which does what I

I have a list of maps that I have already sorted by one type but now I want to further sort that list Original sort Collections.sort(list, new Comparator<Map<String,Object>>(){ @Override p

I have following code for bubble sort but its not sorting at all. if I remove my boolean then its working fine. I understand that since my a[0] is lesser than all other elements therefore no swapping

Why 0 is not returned by the following filter ? [0, 5, 4].sort().filter(function(i){return i}) // returns : [4, 5]

I've had trouble with the examples in the PHP manual, so I'd like to ask this here... I have an array of objects.. Is there a way to sort it based on the contents of the object? For example, my array

Then I perform allValues I have array of strings, but they sorted alphabetically. How can I get array of objects sorted by their placement order ? Second question: how can I sort this objects for key

THIS QUESTION STILL HAS NOT BEEN CORRECTED ANSWERED AS OF Monday Oct 31 (People are wrongly answer it as if I'm asking for array.sort to be modified but I'm not asking that) How do I override the buil

This question already has an answer here: How to randomize (shuffle) a JavaScript array? 16 answers guess I have a list with the next: 20 22 24 how can I sort the three elements randomly so I g

Prove that an array A of size n can be sorted in Θ(n) when it has O(n) inversions. I don't know exactly what this question is asking. My best guess is that we use insertion sort on a presorted input

I'm working on sorted Queues like a Priority Queue. I already did it with a List, and it already worked great. Now I'd like to do it with a array. But I have a little logical Problem with add a new El

I would like to write a piece of code for inserting a number into a sorted array at the appropriate position (i.e. the array should still remain sorted after insertion) My data structure doesn't allow

This question is an extension of a question asked earlier: Least cost path in a sorted array Given a sorted array A e.g. {4,9,10,11,19}. The cost for moving from i->j is abs(A[j] - A[i]) + cost_inc

Note: I'm using ruby 1.9.3 and I can't bring any external dependencies. I have to do this with the core lib. @run_histogram is a Hash of names to an Array of values (two values at this time, :failure,

I am trying to merge and sort 2 arrays in numerical order. function merge_arrays(a, b) { console.log( (a.concat(b)).sort().join( ) ); } This works fine with single digits in an array, but it doesn'

I'm trying to sort an Array of dates from latest to oldest, and unfortunately list.sort (by default) only sorts the first number. My array looks like this: var MyArray = [13 Jun, 09 Jun, 25 Aug,

I've created an array in JavaScript and inserted objects with keys of object_ids: var ar = []; ar[4] = 'a'; ar[2] = 'b'; ar[8] = 'c'; ar[5] = 'd'; Problem is when I print this out the array I get is:

I'm trying to adapt this c++ implementation of the famous kth element of two sorted array algorithm to my application (where the second array is sorted in increasing order). Now, I can see two solutio

I am sorting an NSMutableArray on my field date but it does not take into account the time. If the date is the same, the time is still sorted random. What am I doing wrong? The field date is of th

Is there any built-in JavaScript function to do a partial sort? If not, what is a good way to implement it? Given an unsorted array of N elements, I would like to find K elements that are minimal with

I am trying to write the Array.sort method in my own way using recursive logic. My code is as follows: def sorting_array(unsorted,sorted) temp=unsorted if unsorted.length==0 return sorted elsif unsort

This is my array: $arr = array(-3, -4, 1, -1, 2, 4, -2, 3); I want to sort it like this: 1 2 3 4 -1 -2 -3 -4 So first there would be values greated than zero sorted from the lowest value to the high

Given an 2-D Array of n*n elements: all rows are sorted all columns are sorted For example: 1 5 7 2 6 8 3 9 10 convert it to a 1-D sorted array. Is there a solution better than O(nlog(n)).

I'm struggling on this one. I have an array that contains countries and regions. I want to sort both sets of information in ascending order on the key. Here is the array I'm working with: Array ( [Cou

Given a matrix with m rows and n columns, each of which are sorted. How to efficiently sort the entire matrix? I know a solution which runs in O(m n log(min(m,n)). I am looking for a better solution.

This question already has an answer here: How to sort an array of objects with jquery or javascript [duplicate] 6 answers There is an array emails having few attributes To, From, Subject, Descr

I want to sort a php array in a way that it compares to a certain string and Exact match of the string is in the top the rest need to be sorted according to relevance to the string. The most similar

I am not using an associative array. I'm using 1d array like this, array(1,a,5,b,2,c,8,d,6,f); How can I sort this array? The result should be, array(1,a,2,c,5,b,6,f,8,d);

Consider the data block below, how can I maintain sorted the array by the 3rd field, and keep pushing items? $VAR1 = [ '1111', 'http://...', 3 #this is one of the 3rd field mentioned above ]; $VARN =

beginner here! Recently stumbled upon a problem. Basically, the program needs to sort an array of objects by one of their fields without actually using the sort function. I've tried this code using bu

What is an elegant way to take a javascript array, order by the frequency of the values, and then filter for uniques? So, [apples, oranges, oranges, oranges, bananas, bananas, oranges] b

I am trying to sort one array, but have a second array stay in sync with the first. Example: var a1 = [human, animal, plant]; var a2 = [person, beast, nature]; a1.sort(); After the sort I

How would you sort a multidimensional array in JavaScript? I have an array full of arrays that contain two dates and a string. I need the main array sorted by one of the date arrays, is this possible?