Thomas
Thomas

Reputation: 79

Google Apps Script: Return array with columns specified in another array

I would like to return columns from an array where the column numbers are specified in another array.

We have Array 2, and would like to reduce it to the columns as specified in Array 1.

array2 = [[66,55,44,33,22,11],[77,88,99,55,22,11]];
array1 = [1,3,4];

The output should be:

[[55,33,22],[88,55,22]];

What I've Tried

I feel like I almost have the formula but not quite. Using the below:

  var array1 = [1,3,4];
  var array2 = [[66,55,44,33,22,11],[77,88,99,55,22,11]];
  
  var array3 = array1.map( function (e) { return array2.map(function (f) { return f[e] } )});
  
  console.log(array3)
I end up transforming array2 columns into rows so the output looks like [[55.0, 88.0], [33.0, 55.0], [22.0, 22.0]]

What am I doing wrong?

Upvotes: 1

Views: 440

Answers (1)

Satish Shr
Satish Shr

Reputation: 446

Try using following code. I think it's what you want:

array2.map(arr => array1.map(index => arr[index]));

Upvotes: 3

Related Questions