1

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?

1
  • You would like to map the other array like this : array2.map(e=>array1.map(e2=>e[e2])); Commented Apr 18, 2020 at 15:59

1 Answer 1

3

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

array2.map(arr => array1.map(index => arr[index]));
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.