Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

90
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda