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 nth from last.
For example: If the array is −
const arr = [1, 2, 3, 4, 5, 6];
Then the output should be −
const output = [[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 < upto; i++){ res.push([arr[i], arr[arr.length-1-i]]); }; if(arr.length % 2 !== 0){ res.push([arr[Math.floor(arr.length / 2)]]); }; return res; }; console.log(edgePairs(arr));
Output
The output in the console will be −
[ [ 1, 6 ], [ 2, 5 ], [ 3, 4 ] ]