i have following code:
//data_r array values var = 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 end, sort_order array contains actions performed when sorted items. if want sort second array same way first can following:
//data_x array values var = 0; data_x.sort(function (a,b) { i++; return sort_order[i-1]; });
now data_x array sorted same way data_r array.
the question is, how can undo sort on data_r array?
the following code incorrect:
var unsort = new array(); for(var = 0; < data_r.length; i++) unsort[i] = sort_order[i]*(-1);//-1 perfom oposite action
why, please?
edit:
i can't make copy of array.
i have array #1. sort it.
then receive array #2 but array sorted based on array #1.
i need reverse sorting on array #2.
edit 2:
array #1 = {9, 5, 3, 0, 2}
i sort array #1:
array #1 = {0, 2, 3, 5, 9}
now receive array #2 sorted based on array #1:
array #2 = {"home", "car", "train", "pc", "mouse"}
i need make array #2 this:
array #2 = {"mouse, "pc", "train", "home", "car"}
solved: http://jsfiddle.net/fqm3a/
see @duskwuff's answer on why approach doesn't work.
instead, introduce mapping between original data , sorted data.
{0:2, 1:3, 2:1, 3:0}
which means first element became third, second became last , on. below we'll use array instead of object.
why map help? can sort like dataset using indizes in pointers data you're going compare. , can apply mapping on other datasets. , can reverse mapping easily. see in code:
// data_r, data_x arrays values var l = data_r.length; var sort_order = new array(l); (var i=0; i<l; i++) sort_order[i] = i; // initialised 1-1 mapping // change sort_order first: sort_order.sort(function (a,b) { // , b being indices return data_r[a] - data_r[b]; });
// making new, sorted array var data_x_sorted = new array(l); (var i=0; i<l; i++) data_x_sorted[ sort_order[i] ] = data_x[i]; // put sorted position
if want sort data_x
array itself, use "apply" algorithm showed data_r
.
the question is, how can undo sort on
data_r
array?
either don't sort @ all, , make copy of gets sorted (or nothing @ all).
or use sort_order
reverse it. need swap i
, newindex
(sortorder[i]
) everywhere. example building new, "unsorted" (old-order) array:
var unsorted = new array(l); (var i=0; i<l; i++) unsorted[i] = data_r[ sort_order[i] ]; // take new position
Comments
Post a Comment