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

92
Vistas
Select and pair leftmost and rightmost elements in an array

I have an array e.g [0,1,2,3,4,5] the length will always be even.

How do I select and pair starting from the leftmost and rightmost elements all the way to the center position?

In the above array it should result [[0,5],[1,4],[2,3]]

I have tried this so far... here

const arr = [0,1,2,3,4,5]

const result = []
const possibleMatches = arr.length / 2

for (let x = 0; x < possibleMatches; x++) {
  result.push([arr[x], arr[arr.length - x - 1]])
}

console.log(result)
//[ [ 0, 5 ], [ 1, 4 ], [ 2, 3 ] ]

However, I think they must be better approach than for loop? like using one line arrow function e.t.c?

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

0

You can split the array in half (with Array.splice), then map over the array and use the same logic as you did in your for loop to get the item on the "right" side:

const arr = [0, 1, 2, 3, 4, 5]

const result = arr.splice(0, arr.length / 2).map((e, i) => [e, arr[arr.length - i - 1]])

console.log(result)

about 4 years ago · Juan Pablo Isaza Denunciar

0

take the second half of the array, flip it and merge it with the first half.

here's the one liner.

const arr = [0,1,2,3,4,5]

const result = arr.slice(arr.length / 2 * -1).reverse().map((element, index) => [arr[index],element])
const possibleMatches = arr.length / 2

console.log(result)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use Array.from() to create an array with half the size of the original, and take the values from the start and end of the original array:

const arr = [0,1,2,3,4,5]

const result = Array.from(
  { length: Math.ceil(arr.length / 2) },
  (_, i) => [arr[i], arr[arr.length - 1 - i]]
)

console.log(result)

You can use Array.at() (if supported) to reduce the need for length calculations:

const arr = [0,1,2,3,4,5]

const result = Array.from(
  { length: Math.ceil(arr.length / 2) },
  (_, i) => [arr.at(i), arr.at(-i-1)]
)

console.log(result)

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