challote
challote

Reputation: 35

How create two dimensional (2D) string array dynamic in JavaScript

If the word is ABC

A[0][0]="AA"   A[0][1]="AB"   A[0][2]="AC"
A[1][0]="BA"   A[1][1]="BB"   A[1][2]="BC"
A[2][0]="CA"   A[2][1]="CB"   A[2][2]="CC"

using for, string or array method.

Upvotes: 0

Views: 68

Answers (2)

jcbdrn
jcbdrn

Reputation: 1125

An odd request. Is this what you are looking for?

const word = "ABC";
const letters = word.split("");
const array = [];
letters.forEach((letter1,index1) => {
  letters.forEach((letter2,index2) => {
     if (!array[index1]) {
        array[index1] = [];
     }
     array[index1][index2] = letter1+letter2;
  });
});
console.log(array);

UPDATE:

Another version using older Javascript. Also, check out Asaf's solution using a more functional approach below, is very elegant.

var word = "ABC";
var letters = word.split("");
var array = [];
for(var index1 = 0;index1!==letters.length;index1++) {
  for(var index2 = 0;index2!==letters.length;index2++) {
     if (!array[index1]) {
        array[index1] = [];
     }
     array[index1][index2] = letters[index1]+letters[index2];
  }
}
console.log(array);

Upvotes: 0

Asaf Aviv
Asaf Aviv

Reputation: 11800

const a = [..."ABC"];

console.log(
  a.map(l => a.map(c => l + c))
);

Upvotes: 1

Related Questions