How to loop over this 2D array and build sentences as per given column indexes?

Hello!
I’ve tried getting help elsewhere, but no luck so far.
Given the 2D array of words below, how can I generate sentences, according to the indexes?

let ar = [
  ["Training", "für", "die", "Polizei"],
  ["Trainings", "", "das", "Polizisten"],
  ["Trainingseinheit", "", "", "Militär"]
];

const indexes = [0, 3, 2, 1];

let result = [];
for (let a = 0; a < ar.length; a++) {
  let sentence = [];
  indexes.forEach(function(index) {
    const col = ar.map(e => e[index]).flat();
    for (let c = 0; c < col.length; c++) {
      if (ar[c] == '') {
        c++
        continue;
      } else {
        sentence.push(ar[c]);
      }
    }
  })
  result.push(sentence)
}

This is the expected result:

let result = [
  ["Training für die Polizei"],
  ["Training für die Polizisten"],
  ["Training für die Militär"],
  ["Training für das Polizei"],
  ["Training für das Polizisten"],
  ["Training für das Militär"],
  ["Trainings für die Polizei"],
  ["Trainings für die Polizisten"],
  ["Trainings für die Militär"],
  ["Trainings für das Polizei"],
  ["Trainings für das Polizisten"],
  ["Trainings für das Militär"]...
]

I think it needs recursion, but being a beginner, it’s still hard for me. I would appreciate any help!

I would not use recursion at all. You could, if you wanted to, but you would need to rework this into a function.

Can you better articulate what is supposed to happen with the blank strings?

1 Like

Hello @JeremyLT ! Thanks for your comment. For example, 2nd column only has one word, but that would be in all the sentences beginning with Training until sentences including all words in columns 3 and 4 are created.

The function does give the result with 15 sentences, but the expected result is to contain 30, including, for example:
Training für das Polizei
Training für die Polizisten
Training für die Militär …:

let ar = [
  ['Training', 'für', 'die', 'Polizei'],
  ['Trainings', '', 'das', 'Polizisten'],
  ['Trainingseinheit', '', '', 'Militär'],
];

let result = [];

ar.forEach((el, index) => {
  let sentence = [el[0]];
  
  ar.forEach(el1 => {
    for(let i = 1; i < el1.length; i++) {
      if(el1[i]) {
        sentence[i] = el1[i]
      }
    }
    result.push(sentence.join(' '))
  })
});
console.log(result);

Here is a Fiddle, in case you feel like blessing it with your knowledge!

Much appreciated!

Please provide a more detailed explanation of the problem.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.