0

I am trying to sort only the first dimension of a two-dimensional array

I have

arr = [a,b,c,a,b,c,a,b,c]

arr1 = arr.sort() --> arr1 = [a,a,a,b,b,b,c,c,c]

result = transpose([arr1,arr]) 

Which gives

result = [[[a],[a]],[[a],[a]],[[a],[a]],[[b],[b]],[[b],[b]],[[b],[b]],[[c],[c]],[[c],[c]],[[c],[c]]]

But I need (and expected)

result = [[[a],[a]],[[a],[b]],[[a],[c]],[[b],[a]],[[b],[b]],[[b],[c]],[[c],[a]],[[c],[b]],[[c],[c]]]

Thanks

xyz
  • 2,253
  • 10
  • 46
  • 68
  • From [this](https://stackoverflow.com/questions/29050004/modifying-a-copy-of-a-javascript-object-is-causing-the-original-object-to-change), you'll see that when you sort *arr*, both *arr* and *arr1* get sorted. – ADW Jul 08 '19 at 15:57

1 Answers1

2

You need to make an actual clone of the array, arr is being sorted in what you are doing.

try this:

arr = [a,b,c,a,b,c,a,b,c]

arr1 = arr.slice(0);
arr1.sort();

result = transpose([arr1,arr]) 

My testing is limited because transpose isn't a GAS function and you didn't include it.

Actually with, this, it seems to work:

function transpose(a)
{
  return Object.keys(a[0]).map(function (c) { return a.map(function (r) { return r[c]; }); });
}
J. G.
  • 1,922
  • 1
  • 11
  • 21