2
votes

Créer un tableau 2D à partir d'éléments appariés de deux tableaux 1D en JavaScript

const A = [1,2,3,4,5]
const B = [6,7,8,9,10]
const C = [];
for (let j=0; j<A.length;j++){
  C[j] = C[[A[j],B[j]]
}

Je souhaite créer un tableau 2D C tel que
C = [[1,6], [2,7], [3,8], [4,9], [5,10]]


0 commentaires

6 Réponses :


1
votes

Essayez ceci:

const A = [1,2,3,4,5]
const B = [6,7,8,9,10]
const C = A.map((_,i)=>[A[i],B[i]])
console.log(C);


0 commentaires

1
votes

Il vous suffit de C [[A [j], B [j]] corriger cette ligne. Par cette ligne, vous essayez d'accéder à un index [A [j], B [j]] dans C qui est ( undefined ) pas ce que tu veux

const A = [1,2,3,4,5]
const B = [6,7,8,9,10]
const C = [];
for (let j=0; j<A.length;j++){
 C[j] = [A[j],B[j]]
}

console.log(C)


0 commentaires

1
votes

doit remplacer C [j] = C [[A [j], B [j]] par C [j] = [A [j], B [j] ] . Parce que C [[A [j], B [j]] est non défini

const A = [1,2,3,4,5]
const B = [6,7,8,9,10]
const C = A.map((item, i) => ([item,B[i]]));
console.log(C);

Meilleure façon:

en utilisant map ()

const A = [1,2,3,4,5]
const B = [6,7,8,9,10]
const C = [];
for(let j = 0;j<A.length;j++){
  C[j] = [A[j],B[j]];
}
console.log(C)


0 commentaires

1
votes
const A = [1,2,3,4,5]
const B = [6,7,8,9,10]
const C = [];
for (let j=0; j<A.length;j++){
 C.push([A[j],B[j]]);
}
At the 5th line, we're creating an array of 2 values (one from A and one from B) and after that push the array into the A array.
Very simple,NO?

1 commentaires

Utiliser for loop et Array.prototype.push () sur chaque boucle ce n'est pas simple du tout



1
votes

Vous pouvez utiliser Array.prototype. map ()

Code:

const A = [1,2,3,4,5]
const B = [6,7,8,9,10]
const C = A.map((item, index) => ([item, B[index]]));

console.log(C);


0 commentaires

1
votes

Ce que vous recherchez est un algorithme de transposition pour changer de ligne en colonne, si vous prenez les deux tableaux donnés comme un nouveau tableau avec des lignes.

.as-console-wrapper { max-height: 100% !important; top: 0; }
const
    transpose = array => array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []),
    a = [1, 2, 3, 4, 5],
    b = [6, 7, 8, 9, 10],
    c = transpose([a, b]);

console.log(c);


0 commentaires