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

89
Views
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 answers
Answer question

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 Report

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 Report

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 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!