Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Pairing an array from extreme ends in 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 the array is ?
const arr = [1, 2, 3, 4, 5, 6];
Then the output should be ?
[[1, 6], [2, 5], [3, 4]]
Example
The code for this will be ?
const arr = [1, 2, 3, 4, 5, 6];
const edgePairs = arr => {
const res = [];
const upto = arr.length % 2 === 0 ? arr.length / 2 : arr.length / 2 - 1;
for(let i = 0; i
Output
The output in the console will be ?
[ [ 1, 6 ], [ 2, 5 ], [ 3, 4 ] ]
How It Works
The function works by:
- Calculating how many pairs can be formed by dividing array length by 2
- Looping through the first half and pairing each element with its corresponding element from the end
- For odd-length arrays, the middle element forms a single-element array
Example with Odd Length Array
const oddArr = [1, 2, 3, 4, 5]; console.log(edgePairs(oddArr));
[ [ 1, 5 ], [ 2, 4 ], [ 3 ] ]
Conclusion
This approach efficiently pairs array elements from extreme ends by iterating through half the array and matching indices. For odd-length arrays, the middle element remains unpaired.
Advertisements
