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

1
  • From this, you'll see that when you sort arr, both arr and arr1 get sorted. Commented Jul 8, 2019 at 15:57

1 Answer 1

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]; }); });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.