Home > Mobile >  How can I generate a new 2D array based on existing array following index criteria in JS?
How can I generate a new 2D array based on existing array following index criteria in JS?

Time:11-21

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.

CodePudding user response:

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);

  • Related