Beginning and end pairs in array - JavaScript

We are required to write a JavaScript function that takes in an array of Number / String literals and returns another array of arrays. With each subarray containing exactly two elements, the nth element from start and nth from last.

For example, if we have an array:

const arr = [1, 2, 3, 4, 5, 6];

Then the output should be:

const output = [[1, 6], [2, 5], [3, 4]];

How It Works

The algorithm pairs elements from both ends of the array moving inward:

  • First element (index 0) pairs with last element (index length-1)
  • Second element (index 1) pairs with second-to-last element (index length-2)
  • Continue until we reach the middle

Example

Following is the code:

const arr = [1, 2, 3, 4, 5, 6];

const edgePairs = arr => {
    const res = [];
    const upto = arr.length % 2 === 0 ? arr.length / 2 : (arr.length - 1) / 2;
    
    for(let i = 0; i < upto; i++){
        res.push([arr[i], arr[arr.length - 1 - i]]);
    }
    
    // Handle odd-length arrays - middle element goes alone
    if(arr.length % 2 !== 0){
        res.push([arr[Math.floor(arr.length / 2)]]);
    }
    
    return res;
};

console.log(edgePairs(arr));
[ [ 1, 6 ], [ 2, 5 ], [ 3, 4 ] ]

Handling Odd-Length Arrays

When the array has an odd number of elements, the middle element cannot be paired and forms a single-element subarray:

const oddArr = [1, 2, 3, 4, 5];

console.log(edgePairs(oddArr));
[ [ 1, 5 ], [ 2, 4 ], [ 3 ] ]

Alternative Approach

Here's a cleaner version that handles both even and odd arrays more elegantly:

const edgePairsSimple = arr => {
    const result = [];
    const length = arr.length;
    
    for(let i = 0; i < Math.ceil(length / 2); i++){
        if(i === length - 1 - i) {
            // Middle element in odd-length array
            result.push([arr[i]]);
        } else {
            result.push([arr[i], arr[length - 1 - i]]);
        }
    }
    
    return result;
};

console.log("Even array:", edgePairsSimple([1, 2, 3, 4]));
console.log("Odd array:", edgePairsSimple([1, 2, 3, 4, 5]));
Even array: [ [ 1, 4 ], [ 2, 3 ] ]
Odd array: [ [ 1, 5 ], [ 2, 4 ], [ 3 ] ]

Conclusion

This function creates pairs from opposite ends of an array moving toward the center. For odd-length arrays, the middle element forms a single-element pair, ensuring all elements are included in the result.

Updated on: 2026-03-15T23:18:59+05:30

177 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements