0

Given this array below, each word in the first column would generate a new row containing the elements from the other columns. So this array whose length is 3 would be 9.

Original Array

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

Code

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

let indexes = [0, 1, 2, 3]; //Dynamically built, so the order and length may change
let separators = [' ', ' ', ' ', ' '];

let result = [];
indexes.forEach(function(index) {
  for (let a = 0; a < ar.length; a++) {
    let sentence = [];
    for (let r = 1; r <= ar[a].length; r++) {
      if (r > 1) {
        let words = ar[a][index];
        if (words != '') {
          result.push(words)
        }
      }
    }
  }
})
console.log(result)

Expected Result

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

Being a beginner, I've been stuck in this one and would appreciate some help.

onit
  • 2,275
  • 11
  • 25

1 Answers1

1

is this what are you looking for?

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);
Georgemff
  • 104
  • 6
  • Exactly. Thanks a million!!! – onit Nov 20 '22 at 19:22
  • I guess it'd be ```result.push([sentence.join(' ')])``` if it's to be a 2D array as a result, right? – onit Nov 20 '22 at 20:04
  • if you want to that string be in the array, then yes – Georgemff Nov 20 '22 at 20:06
  • Hi! I got one variation of this answer pending as the code above actually misses some elements, while generating the sentences. I've created a question [here](https://stackoverflow.com/q/74645779/11832197), but I would even be willing to pay for the tweak in the code to make it happen, if need be. Let me know. Thanks for your attention. – onit Dec 05 '22 at 11:39