Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
JavaScript get array of pairs of consecutive values

how can I convert an array like:

[2, 5, 4, 0]

into an array of pairs but not getting every pair. For example from the above array given, I'd like the following array:

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

Furthermore, is it possible to have another function that gives back an array like: [[2,5,4],[5,4,0],[4,0,2],[0,2,5]]?

And also another one that gives back: [[2,5,4,0],[5,4,0,2],[4,0,2,5],[0,2,5,4]]?

Edit: I have tried the following which gives back every possible pair in the array, but it's not what I'm looking for:

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

This will show: [ [ 2, 5 ], [ 2, 4 ], [ 2, 0 ], [ 5, 4 ], [ 5, 0 ], [ 4, 0 ] ]

Edit2: my problem here is that everything I have tried gives me every permutation of the two dimensional, three dimensional and four dimensional arrays, but I only want the examples above. Let's say, the permutation of consecutive values.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I believe this is what you are looking for:

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 Denunciar

0

Here is one way to do it:

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda