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

Join three arrays to make one array which is a combination of a Cartesian product of rows with cols and dynamic relation with cells

developers; I have three arrays: Days (columns), Subject (rows), Data(cells)

let Days = ["Monday", "Tuesday", "Wednesday"];
let Subject = [
  "Economics",
  "geography",
  "theatre",
  "music",
  "mathematics",
  "psychology",
  "marketing",
  "business",
  "journalism",
  "languages",
];
const Data = [
  ["10:00", "12:10", "13:30"],
  ["08:30", "12:10", "14:30"],
  ["14:10", "15:15", "19:10"],
  ["20:20", "20:50", "23:00"],
  ["09:10", "10:00", "19:00"],
  ["10:12", "16:40", "18:10"],
  ["08:30", "12:10", "14:30"],
  ["14:10", "15:15", "19:10"],
  ["20:20", "20:50", "23:00"],
  ["08:10", "14:20", "20:20"],
];

I wanna make a relation between those arrays:

I’ve tried something like playing with modulo and looping over product of rows and cells:

const cols = Days.length;
const rows = Subject.length;
const len = Subject.length * Days.length;
const table = [];
for (let i = 0, j = 0; i < len; i++) {
  table.push([
    Subject[i % rows],
    Days[j % cols],
    Data[i % rows][j % cols],
  ]);
  j++;
}
console.table(table);

But it gives results not expected in order:

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

I still trying to sorting it but does not work since sorting would sort in alphabet order which doesn’t keep the order?

console.table(table.sort((a, b) => a[0].localeCompare(b[0])));

Thanks in advance, any suggestions are welcome and appreciated

>Solution :

Simply by doing the sort while doing the product process, as follows:

for (let i = 0; i < rows; i++) {
  for (let j = 0; j < cols; j++) {
      table.push([
      Subject[I],
      Days[j],
      Data[i][j],
      ]);
   }
 }

In this case, you will be iterating each row from Subject with all the corresponding values from Days, before moving to the next row of Subject, ending with the desired order of elements.

For example:
  the first iteration will be as follows (representing the first three row of the resulting array)
     i = 0  (Subject[i] = "Economics")
       j = 0  (Days[j] = "Monday") ---> Data[i][j] = "10:00"   
       j = 1  (Days[j] = "Tuesday") ---> Data[i][j] = "12:10"
       j = 2  (Days[j] = "Wednesday") ---> Data[i][j] = "13:30"
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