Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

245
Views
Mezclar matrices anidadas en Javascript

Estoy tratando de ordenar varias matrices dentro de una matriz (que también debe barajarse). Un ejemplo simplificado es:

 let toShuffle = [ [1, 2, 3, 4, 5], [9, 8, 7, 6, 5], [10, 67, 19 ,27] ... ]; const shuffled = shuffle(toShuffle); // outout would look something like: // [ // [8, 6, 5, 7, 9], // [4, 3, 1, 5, 2], // [19, 26, 10, 67], // ... // ]

Esto debe ser flexible, por lo que cualquier cantidad de matrices con cualquier cantidad de valores debería ser válida.

Esto es lo que he probado:

 function shuffle(a) { for (let e in a) { if (Array.isArray(a[e])) { a[e] = shuffle(a[e]); } else { a.splice(e, 1); a.splice(Math.floor(Math.random() * a.length), 0, a[e]); } } return a; } console.log("Shuffled: " + shuffle([ [1, 2, 3, 4, 5], [5, 4, 3, 2, 1] ]))

Pero no está funcionando según lo previsto. ¿Es su una manera más fácil de hacer esto? ¿O mi código es correcto y solo tiene errores?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Casi lo tienes. El problema es que está eliminando un elemento de una matriz, en lugar de capturar el elemento eliminado y colocarlo en una posición aleatoria:

 let toShuffle = [ [1, 2, 3, 4, 5], [9, 8, 7, 6, 5], [10, 67, 19 ,27] ]; function shuffle(a) { a = [...a]; //clone array for (let e in a) { if (Array.isArray(a[e])) { a[e] = shuffle(a[e]); } else { a.splice(~~(Math.random() * a.length), 0, a.splice(e, 1)[0]); } } return a; } console.log(JSON.stringify(shuffle(toShuffle))) console.log(JSON.stringify(toShuffle))

[EDITAR] El código original no barajó la matriz principal, si necesita barajar todo recursivamente, puede usar esto:

 let toShuffle = [ [1, 2, 3, 4, 5], [9, 8, 7, 6, 5], [10, 67, 19 ,27] ]; function shuffle(a) { a = a.map(i => Array.isArray(i) ? shuffle(i) : i); //clone array a.sort(i => ~~(Math.random() * 2) - 1); //shuffle return a; } console.log("shuffled", JSON.stringify(shuffle(toShuffle))) console.log("original", JSON.stringify(toShuffle))

about 4 years ago · Juan Pablo Isaza Report

0

Puede usar Array.from() para crear una nueva array de copia superficial y luego mezclar Array.prototype.sort() combinado con Math.random()

Código:

 const toShuffle = [ [1, 2, 3, 4, 5], [9, 8, 7, 6, 5], [10, 67, 19 ,27] ] const shuffle = a => Array.from(a).sort(() => .5 - Math.random()) const result = toShuffle.map(shuffle) console.log('Shuffled:', JSON.stringify(result)) console.log('To shuffle:', JSON.stringify(toShuffle))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!