Click here to Skip to main content
15,566,394 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can I generate an array like this:
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"],
  ...
]


...from an array of words, like the one in the attempt below?

What I have tried:

JavaScript
<pre>let ar = [
  ["Training", "für", "die", "Polizei"],
  ["Trainings", "", "das", "Polizisten"],
  ["Trainingseinheit", "", "", "Militär"]
]

let indexes = [0, 1, 2, 3]; //The order and length may change
let separators = [' ', ' ', ' ', ' '];
let result = [];
ar = ar.map(x => indexes.map(e => x.slice()[0] = x[e]));
for (let row = 0; row < ar.length; row++) {
  let word = ar[row][0];
  
  for (let col = 1; col <= ar[row].length - 1; col++) {
    const colLength = ar.map(e => e[col]).filter(e => e != '').length
    let sentence = [];

    for (let val = 0; val <= colLength; val++) {
      let words = ar[val];
      if (words != '') {
        sentence.push(words)
      }
    }
    result.push(sentence)
  }
}
console.log(result)
Posted
Comments
Richard MacCutchan 7-Nov-22 7:13am    
You need to know the order of the words, which is not always straightforward.
santosonit 7-Nov-22 7:23am    
Hi! Thanks for your comment. The indexes should dictate the order of the words.
Gerry Schmitz 8-Nov-22 10:44am    
You need at least 3 arrays in the direction you're going: subjects, verbs, objects.

Then with 3 random numbers, you can create a random 3 word sentence of: subject[i] + " " + verb[j] + " " + object[k].
santosonit 15-Nov-22 13:48pm    
Hi, The issue with that is because the number of words (subject, verb, object, etc) may vary. Thanks for your comment!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900