Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript Object creation from two array

Suppose I have two array:

days = [3, 5, 7, 9]
values = [[13, 15, 17, 19], [14, 16, 18, 20]]

What I want is create another 2 dimensional array with the following manner:

  1. Say I choose day = 5
  2. Create an array as [[15, 15, 15, 15], [16, 16, 16, 16]]

What I am doing here is for day = 5, the 1st array has value 15, so the created array will have the 1st array filled with 15 and for the second array (similarly) with 16.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In python this would be easy:

days = [3, 5, 7, 9]
values = [[13, 15, 17, 19], [14, 16, 18, 20]]
day_index = days.index(5)
res = [[i[day_index]] * len(i) for i in values]

How to accomplish that in javascript? I can get the index with indexOf, but having trouble with the second part.

>Solution :

Try this one

const days = [3, 5, 7, 9];
const values = [[13, 15, 17, 19], [14, 16, 18, 20]];
const dayIndex = days.indexOf(5);
const res = values.map(arr => Array(arr.length).fill(arr[dayIndex]));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading