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?
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)
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)
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)