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

146
Views
JavaScript obtiene una matriz de pares de valores consecutivos

¿Cómo puedo convertir una matriz como:

[2, 5, 4, 0]

en una matriz de pares, pero sin obtener todos los pares. Por ejemplo, de la matriz anterior dada, me gustaría la siguiente matriz:

[[2, 5],[5, 4], [4, 0], [0, 2] .

Además, ¿es posible tener otra función que devuelva una matriz como: [[2,5,4],[5,4,0],[4,0,2],[0,2,5]] ?

Y también otro que devuelve: [[2,5,4,0],[5,4,0,2],[4,0,2,5],[0,2,5,4]] ?

Editar: he intentado lo siguiente que devuelve todos los pares posibles en la matriz, pero no es lo que estoy buscando:

 let result = pieces[0].reduce( (acc, v, i) => acc.concat(pieces[0].slice(i+1).map( w => [v, w] )), []);

Esto mostrará: [ [ 2, 5 ], [ 2, 4 ], [ 2, 0 ], [ 5, 4 ], [ 5, 0 ], [ 4, 0 ] ]

Edit2: mi problema aquí es que todo lo que he intentado me da todas las permutaciones de las matrices bidimensionales, tridimensionales y tetradimensionales, pero solo quiero los ejemplos anteriores. Digamos, la permutación de valores consecutivos.

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

0

Creo que esto es lo que estás buscando:

 let arr = [2, 5, 4, 0] function getPermutation(chunk){ let result = arr.reduce((acc,e,i) => { if(i + chunk <= arr.length) acc.push(arr.slice(i,i+chunk)) else acc.push(arr.slice(i,i+chunk).concat(arr.slice(0,(i+chunk) % arr.length))) return acc; },[]) return result } console.log(getPermutation(2)) console.log(getPermutation(3)) console.log(getPermutation(4))

about 4 years ago · Juan Pablo Isaza Report

0

Aquí hay una manera de hacerlo:

 const input = [2, 5, 4, 0]; const output = []; for(let i=0; i<input.length - 1; i++) { output.push([input[i], input[i+1]]); } output.push([input[input.length-1], input[0]]); console.log(output);

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!